<?php

declare(strict_types=1);

namespace App\Models;

use Database\Factories\ReportJobFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Задание на генерацию отчёта (schema §13.5).
 *
 * Status flow: pending → processing → done|failed.
 * UI mock использует queued/running — backend отдаёт schema-канон.
 *
 * `type` — slug генератора (deals_export, managers_summary, sources_summary,
 * billing_summary). `parameters` — JSONB {format, date_from, date_to, project_id?,
 * manager_id?, retry_count?}.
 *
 * Триггер `trg_report_jobs_export_log` пишет audit-запись в pd_processing_log
 * AFTER INSERT (см. schema §13.5). UPDATE/DELETE триггеров нет.
 *
 * @mixin IdeHelperReportJob
 */
class ReportJob extends Model
{
    /** @use HasFactory<ReportJobFactory> */
    use HasFactory;

    public const STATUS_PENDING = 'pending';

    public const STATUS_PROCESSING = 'processing';

    public const STATUS_DONE = 'done';

    public const STATUS_FAILED = 'failed';

    public const ACTIVE_STATUSES = [self::STATUS_PENDING, self::STATUS_PROCESSING];

    public const TERMINAL_STATUSES = [self::STATUS_DONE, self::STATUS_FAILED];

    public const TYPES = [
        'deals_export',
        'managers_summary',
        'sources_summary',
        'billing_summary',
    ];

    public const FORMATS = ['csv', 'xlsx', 'json', 'pdf'];

    public const UPDATED_AT = null;

    protected $fillable = [
        'tenant_id',
        'user_id',
        'type',
        'parameters',
        'status',
        'file_path',
        'file_size',
        'generation_seconds',
        'error_message',
        'finished_at',
        'expires_at',
    ];

    protected function casts(): array
    {
        return [
            'tenant_id' => 'integer',
            'user_id' => 'integer',
            'parameters' => 'array',
            'file_size' => 'integer',
            'generation_seconds' => 'integer',
            'created_at' => 'datetime',
            'finished_at' => 'datetime',
            'expires_at' => 'datetime',
        ];
    }

    /** @return BelongsTo<Tenant, $this> */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

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

    public function isActive(): bool
    {
        return in_array($this->status, self::ACTIVE_STATUSES, true);
    }

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

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