<?php

declare(strict_types=1);

namespace Maestro\Core\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Str;
use Maestro\Core\Jobs\ExportDataTableJob;
use Maestro\Core\Support\AuthUserResolver;

/**
 * Async DataTable CSV export row; updated by {@see ExportDataTableJob}.
 */
final class DataTableExport extends Model
{
    public const STATUS_PENDING = 'pending';

    public const STATUS_PROCESSING = 'processing';

    public const STATUS_READY = 'ready';

    public const STATUS_COMPLETED = 'completed';

    public const STATUS_FAILED = 'failed';

    public $incrementing = false;

    protected $keyType = 'string';

    protected $table = 'data_table_exports';

    protected $fillable = [
        'user_id',
        'resource_key',
        'payload',
        'status',
        'file_path',
        'download_expires_at',
        'error_message',
    ];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'payload' => 'array',
            'download_expires_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        self::creating(function (DataTableExport $export): void {
            if (empty($export->id)) {
                $export->id = (string) Str::uuid();
            }
        });
    }

    /** @return BelongsTo<User, DataTableExport> */
    public function user(): BelongsTo
    {
        return $this->belongsTo(AuthUserResolver::eloquentModelClass());
    }

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

    public function isDownloadAvailable(): bool
    {
        return $this->status === self::STATUS_READY
            && $this->file_path
            && $this->download_expires_at
            && $this->download_expires_at->isFuture();
    }
}
