<?php

namespace Maestro\Core\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

/**
 * Async DataTable CSV export record.
 * Created when user starts export; updated by ExportDataTableJob (status, file_path, download_expires_at, error_message).
 * One activity log entry is written manually in the controller (who exported which data, when).
 */
class DataTableExport extends Model
{
    public const STATUS_PENDING = 'pending';

    public const STATUS_PROCESSING = 'processing';

    public const STATUS_READY = 'ready'; /** File is ready on disk and can be downloaded. */

    public const STATUS_COMPLETED = 'completed'; /** Export flow fully completed (user has downloaded the file at least once). */

    public const STATUS_FAILED = 'failed';

    public $incrementing = false;

    protected $keyType = 'string';

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

    protected $casts = [
        'payload' => 'array',
        'download_expires_at' => 'datetime',
    ];

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

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

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

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

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

    public function isDownloadAvailable(): bool
    {
        return $this->isReady()
            && $this->file_path
            && $this->download_expires_at
            && $this->download_expires_at->isFuture();
    }
}
