<?php
namespace App\Models\Marketplace;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class ProductMedia extends Model
{
    use HasFactory;
    protected $table = 'products_media';

    protected $fillable = [
        'product_id',
        'file_path',
        'file_name',
        'file_type',
        'file_size',
        'sort_order',
        'is_primary'
    ];

    protected $casts = [
        'file_size' => 'integer',
        'sort_order' => 'integer',
        'is_primary' => 'boolean'
    ];

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    // Get the full URL of the file
    public function getUrlAttribute()
    {
        if ($this->file_path) {
            return asset('storage/' . $this->file_path);
        }
        return null;
    }

    // Delete the file when the model is deleted
    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($media) {
            if ($media->file_path) {
                Storage::disk('public')->delete($media->file_path);
            }
        });
    }
}
