<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class PatientFile extends Model
{
    use BelongsToTenant, HasFactory, SoftDeletes;

    public const TYPES = ['photo_before', 'photo_after', 'xray', 'other'];

    protected $fillable = [
        'tenant_id', 'patient_id', 'type', 'path', 'thumb_path',
        'original_name', 'mime', 'size', 'teeth', 'caption',
        'paired_with_id', 'treatment_plan_id', 'appointment_id', 'uploaded_by',
    ];

    protected function casts(): array
    {
        return ['teeth' => 'array'];
    }

    protected static function booted(): void
    {
        static::creating(fn (PatientFile $f) => $f->uuid ??= (string) Str::uuid());
    }

    public function patient(): BelongsTo
    {
        return $this->belongsTo(Patient::class);
    }

    /** For an AFTER photo: its BEFORE photo. */
    public function before(): BelongsTo
    {
        return $this->belongsTo(self::class, 'paired_with_id');
    }

    /** For a BEFORE photo: the AFTER photo paired to it. */
    public function after(): HasOne
    {
        return $this->hasOne(self::class, 'paired_with_id');
    }

    public function treatmentPlan(): BelongsTo
    {
        return $this->belongsTo(TreatmentPlan::class);
    }

    public function isImage(): bool
    {
        return str_starts_with($this->mime, 'image/');
    }

    public function sizeFormatted(): string
    {
        return $this->size >= 1048576
            ? round($this->size / 1048576, 1).' MB'
            : round($this->size / 1024).' KB';
    }
}
