<?php

namespace App\Models;

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

class OrderPdf extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'order_id',
        'file_path',
        'file_name',
        'file_size',
        'mime_type',
        'expires_at',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'order_id' => 'integer',
        'file_size' => 'integer',
        'expires_at' => 'datetime',
    ];

    /**
     * Get the order that owns the PDF.
     */
    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class);
    }

    /**
     * Get the full URL to the PDF file.
     */
    public function getUrlAttribute(): string
    {
        return Storage::url($this->file_path);
    }

    /**
     * Get the full storage path to the PDF file.
     */
    public function getFullPathAttribute(): string
    {
        return Storage::path($this->file_path);
    }

    /**
     * Check if the PDF file exists.
     */
    public function exists(): bool
    {
        return Storage::exists($this->file_path);
    }

    /**
     * Delete the PDF file from storage.
     */
    public function deleteFile(): bool
    {
        if ($this->exists()) {
            return Storage::delete($this->file_path);
        }

        return false;
    }

    /**
     * Check if the PDF has expired.
     */
    public function isExpired(): bool
    {
        return $this->expires_at && $this->expires_at->isPast();
    }

    /**
     * Scope a query to only include expired PDFs.
     */
    public function scopeExpired($query)
    {
        return $query->where('expires_at', '<', now());
    }

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        // When deleting the model, also delete the file
        static::deleting(function ($pdf) {
            $pdf->deleteFile();
        });
    }
}
