<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ReelRequest extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'brand_id',
        'status',
        'template',
        'options',
        'job_id',
        'result_path',
        'duration',
        'error_message',
    ];

    protected $casts = [
        'options' => 'array',
        'meta' => 'array',
        'duration' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * Get the user that owns the reel request.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the brand that owns the reel request.
     */
    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }

    /**
     * Get the inputs for the reel request.
     */
    public function inputs()
    {
        return $this->hasMany(ReelInput::class);
    }

    /**
     * Check if the reel is ready.
     */
    public function isReady(): bool
    {
        return $this->status === 'ready';
    }

    /**
     * Check if the reel is processing.
     */
    public function isProcessing(): bool
    {
        return $this->status === 'processing';
    }

    /**
     * Check if the reel has failed.
     */
    public function hasFailed(): bool
    {
        return $this->status === 'failed';
    }

    /**
     * Mark the reel as processing.
     */
    public function markProcessing(): void
    {
        $this->status = 'processing';
        $this->save();
    }

    /**
     * Mark the reel as ready.
     */
    public function markReady(): void
    {
        $this->status = 'ready';
        $this->save();
    }

    /**
     * Mark the reel as failed.
     */
    public function markFailed(string $errorMessage): void
    {
        $this->status = 'failed';
        $this->error_message = $errorMessage;
        $this->save();
    }

    /**
     * Get the signed URL for the result.
     */
    public function getResultUrl()
    {
        if (!$this->result_path) {
            return null;
        }

        return \Storage::disk('public')->exists($this->result_path) 
            ? \Storage::disk('public')->temporaryUrl($this->result_path, now()->addMinutes(config('reels.signed_url_expire', 300)))
            : null;
    }
}