<?php

declare(strict_types=1);

namespace ImovelZapAi\Importing\Infrastructure\Persistence\Eloquent;

use App\Models\User;
use Database\Factories\ImportJobFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use ImovelZapAi\Importing\Domain\Enums\ImportJobStatus;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\BelongsToTenant;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\HasUuidPrimaryKey;

/**
 * @property string $id
 * @property string $tenant_id
 * @property string|null $created_by
 * @property ImportJobStatus|string $status
 * @property array<string, mixed>|null $mapping
 * @property array<string, mixed>|null $preview_summary
 * @property array<string, mixed>|null $report_summary
 */
class ImportJobModel extends Model
{
    use BelongsToTenant;
    use HasFactory;
    use HasUuidPrimaryKey;

    protected $table = 'import_jobs';

    protected $fillable = [
        'tenant_id',
        'created_by',
        'status',
        'format',
        'idempotency_key',
        'total_listings',
        'valid_listings',
        'error_listings',
        'warning_listings',
        'imported_count',
        'updated_count',
        'unchanged_count',
        'ignored_count',
        'failed_count',
        'photos_imported',
        'checkpoint_index',
        'progress_current',
        'progress_total',
        'mapping',
        'preview_summary',
        'report_summary',
        'failure_message',
        'analyzing_started_at',
        'preview_ready_at',
        'queued_at',
        'processing_started_at',
        'completed_at',
    ];

    protected function casts(): array
    {
        return [
            'status' => ImportJobStatus::class,
            'mapping' => 'array',
            'preview_summary' => 'array',
            'report_summary' => 'array',
            'analyzing_started_at' => 'datetime',
            'preview_ready_at' => 'datetime',
            'queued_at' => 'datetime',
            'processing_started_at' => 'datetime',
            'completed_at' => 'datetime',
        ];
    }

    protected static function newFactory(): ImportJobFactory
    {
        return ImportJobFactory::new();
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function file(): HasOne
    {
        return $this->hasOne(ImportFileModel::class, 'import_job_id');
    }

    public function errors(): HasMany
    {
        return $this->hasMany(ImportErrorModel::class, 'import_job_id');
    }

    public function logs(): HasMany
    {
        return $this->hasMany(ImportLogModel::class, 'import_job_id');
    }
}
