<?php

declare(strict_types=1);

namespace App\Models;

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

class NovaCardExport extends Model
{
    public const TYPE_PREVIEW = 'preview';
    public const TYPE_HIRES = 'hires';
    public const TYPE_SQUARE = 'square';
    public const TYPE_STORY = 'story';
    public const TYPE_WALLPAPER = 'wallpaper';
    public const TYPE_OG = 'og';

    public const STATUS_PENDING = 'pending';
    public const STATUS_PROCESSING = 'processing';
    public const STATUS_READY = 'ready';
    public const STATUS_FAILED = 'failed';

    protected $fillable = [
        'card_id',
        'user_id',
        'export_type',
        'status',
        'output_path',
        'width',
        'height',
        'format',
        'options_json',
        'ready_at',
        'expires_at',
    ];

    protected $casts = [
        'options_json' => 'array',
        'width' => 'integer',
        'height' => 'integer',
        'ready_at' => 'datetime',
        'expires_at' => 'datetime',
    ];

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

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

    public function outputUrl(): ?string
    {
        if (! $this->output_path) {
            return null;
        }

        return Storage::disk((string) config('nova_cards.storage.public_disk', 'public'))->url($this->output_path);
    }

    public function isReady(): bool
    {
        return $this->status === self::STATUS_READY;
    }

    public function isExpired(): bool
    {
        return $this->expires_at !== null && $this->expires_at->isPast();
    }
}
