<?php

namespace App\Models;

use App\Enums\DataExportScope;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DataExport extends Model
{
    use HasFactory;

    public const STATUS_PENDING = 'pending';

    public const STATUS_PROCESSING = 'processing';

    public const STATUS_READY = 'ready';

    public const STATUS_FAILED = 'failed';

    public const STATUS_CANCELED = 'canceled';

    protected $fillable = [
        'user_id',
        'tenant_id',
        'event_id',
        'status',
        'scope',
        'include_media',
        'path',
        'size_bytes',
        'expires_at',
        'error_message',
    ];

    protected $casts = [
        'expires_at' => 'datetime',
        'include_media' => 'boolean',
        'scope' => DataExportScope::class,
    ];

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

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

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

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

    public function canRetry(): bool
    {
        return in_array($this->status, [self::STATUS_FAILED, self::STATUS_CANCELED], true);
    }

    public function canCancel(): bool
    {
        return in_array($this->status, [self::STATUS_PENDING, self::STATUS_PROCESSING], true);
    }

    public function resetForRetry(): void
    {
        $this->update([
            'status' => self::STATUS_PENDING,
            'error_message' => null,
            'path' => null,
            'size_bytes' => null,
            'expires_at' => null,
        ]);
    }

    public function markCanceled(?string $reason = null): void
    {
        $this->update([
            'status' => self::STATUS_CANCELED,
            'error_message' => $reason ?: 'Canceled by superadmin.',
            'path' => null,
            'size_bytes' => null,
            'expires_at' => null,
        ]);
    }

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