<?php

declare(strict_types=1);

namespace App\Models;

use Database\Factories\ImportUnknownStatusFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Неизвестный статус воронки из CSV-импорта (schema §6.4, Sprint 4 H1).
 *
 * Tenant-aware модель с RLS. UNIQUE (tenant_id, status_ru): повторный импорт
 * инкрементит occurrences и переиспользует ранее проставленный mapped_to_slug.
 *
 * @mixin IdeHelperImportUnknownStatus
 */
class ImportUnknownStatus extends Model
{
    /** @use HasFactory<ImportUnknownStatusFactory> */
    use HasFactory;

    protected $fillable = [
        'tenant_id',
        'import_log_id',
        'status_ru',
        'occurrences',
        'mapped_to_slug',
        'resolved_at',
        'resolved_by',
    ];

    protected function casts(): array
    {
        return [
            'tenant_id' => 'integer',
            'import_log_id' => 'integer',
            'occurrences' => 'integer',
            'resolved_by' => 'integer',
            'resolved_at' => 'datetime',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

    /**
     * Незамапленные статусы (mapped_to_slug IS NULL) — вход для wizard'а §6.6.
     *
     * @param  Builder<ImportUnknownStatus>  $query
     * @return Builder<ImportUnknownStatus>
     */
    public function scopeUnresolved(Builder $query): Builder
    {
        return $query->whereNull('mapped_to_slug');
    }

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