<?php

namespace App\Models;

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 Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

#[Guarded(['id'])]
#[Appends(['file_url', 'file_name'])]
class Material extends Model implements HasMedia
{
    use HasFactory, InteractsWithMedia, SoftDeletes;

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

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

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

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