<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class AdMedia extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'ad_id',
        'type',
        'media'
    ];

    /**
     * Booted method of the model
     *
     * @return void
     */
    protected static function booted()
    {
        static::deleting(function ($adMedia) {
            $file = config('filesystems.disks.' . env('UPLOADS_DISK') . '.root') . $adMedia->media;

            if (file_exists($file)) {
                unlink($file);
            }
        });
    }

    /**
     * Get the ad media
     *
     * @return Attribute
     */
    protected function media(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => ! is_null($value) ? env('UPLOAD_URL') . $value : null,
        );
    }

    /**
     * Get the ad that owns the media.
     *
     * @return BelongsTo
     */
    public function ad(): BelongsTo
    {
        return $this->belongsTo(Ad::class);
    }
}
