<?php

declare(strict_types=1);

namespace App\Models;

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

/**
 * Raw-payload входящих webhook'ов от поставщика crm.bp-gr.ru.
 *
 * SaaS-level таблица (без RLS) — на момент INSERT'а tenant ещё не определён;
 * routing к Лидерра-проектам происходит в RouteSupplierLeadJob через
 * supplier_project_id + LeadRouter.
 *
 * Spec: docs/superpowers/specs/2026-05-10-supplier-integration-design.md §5.1
 *
 * Поля резолва региона (lead-region) аннотированы явно — ide-helper:models
 * не подхватил их в стаб IdeHelperSupplierLead:
 *
 * @property int|null $dadata_qc
 * @property string|null $phone_operator
 * @property string|null $region_source
 * @property int|null $resolved_subject_code
 *
 * @mixin IdeHelperSupplierLead
 */
class SupplierLead extends Model
{
    /** @use HasFactory<SupplierLeadFactory> */
    use HasFactory;

    protected $table = 'supplier_leads';

    public $timestamps = false;

    protected $fillable = [
        'supplier_project_id',
        'platform',
        'raw_payload',
        'vid',
        'phone',
        'received_at',
        'source',
        'processed_at',
        'recovered_from_csv_at',
        'deals_created_count',
        'error',
        // Lead region resolution (Session 1, 31.05.2026) — persistent idempotency + display.
        'resolved_subject_code',
        'region_source',
        'dadata_qc',
        'phone_operator',
    ];

    protected function casts(): array
    {
        return [
            'raw_payload' => 'array',
            'received_at' => 'datetime',
            'processed_at' => 'datetime',
            'recovered_from_csv_at' => 'datetime',
            'vid' => 'integer',
            'deals_created_count' => 'integer',
            'resolved_subject_code' => 'integer',
            'dadata_qc' => 'integer',
        ];
    }

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

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