<?php

declare(strict_types=1);

namespace App\Models;

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

/**
 * Журнал CSV-импорта (schema §6.7, Sprint 4).
 *
 * Tenant-aware модель с RLS: tenant_isolation по current_setting('app.current_tenant_id').
 * Sprint 4 enrichment: entity_type / source_system / mapping_config / unknown_statuses_count / dry_run.
 *
 * @mixin IdeHelperImportLog
 */
class ImportLog extends Model
{
    /** @use HasFactory<ImportLogFactory> */
    use HasFactory;

    public const UPDATED_AT = null;

    public const CREATED_AT = null;

    protected $table = 'import_log';

    /** Зеркало DB DEFAULT'ов: Laravel не читает их из БД после INSERT без refresh(). */
    protected $attributes = [
        'status' => 'pending',
        'entity_type' => 'leads',
        'source_system' => 'crm.bp-gr.ru',
        'dry_run' => false,
        'unknown_statuses_count' => 0,
        'rows_total' => 0,
        'rows_added' => 0,
        'rows_updated' => 0,
        'rows_skipped' => 0,
    ];

    protected $fillable = [
        'tenant_id',
        'user_id',
        'filename',
        'file_path',
        'rows_total',
        'rows_added',
        'rows_updated',
        'rows_skipped',
        'status',
        'error_message',
        'started_at',
        'finished_at',
        'entity_type',
        'source_system',
        'mapping_config',
        'unknown_statuses_count',
        'dry_run',
    ];

    protected function casts(): array
    {
        return [
            'tenant_id' => 'integer',
            'user_id' => 'integer',
            'rows_total' => 'integer',
            'rows_added' => 'integer',
            'rows_updated' => 'integer',
            'rows_skipped' => 'integer',
            'unknown_statuses_count' => 'integer',
            'dry_run' => 'boolean',
            'mapping_config' => 'array',
            'started_at' => 'datetime',
            'finished_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);
    }
}
