<?php

namespace App\Models;

use App\Enums\LetterStatus;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

#[Guarded(['id'])]
#[Appends(['result_url', 'result_name'])]
class LetterRequest extends Model implements HasMedia
{
    use HasFactory, InteractsWithMedia;

    protected function casts(): array
    {
        return [
            'status' => LetterStatus::class,
            'submitted_at' => 'datetime',
            'completed_at' => 'datetime',
        ];
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('letter_result')->singleFile();
    }

    public function processor(): BelongsTo
    {
        return $this->belongsTo(User::class, 'processed_by');
    }

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

    protected function resultUrl(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->getFirstMediaUrl('letter_result') ?: null,
        );
    }

    protected function resultName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->getFirstMedia('letter_result')?->file_name,
        );
    }
}
