<?php

declare(strict_types=1);

namespace App\Models;

use Database\Factories\SupplierProjectFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

/**
 * Supplier-уровневый агрегат проекта у поставщика crm.bp-gr.ru.
 *
 * Sharing-model: один supplier_project разделяется между несколькими Лидерра-tenant'ами
 * (см. spec §2.2). НЕ tenant-scoped — RLS НЕ применяется.
 *
 * Уникальность: (platform, unique_key). Для site/call: unique_key = домен/номер.
 * Для sms: B2 ключ — sender+keyword (конкатенация), B3 — только sender.
 *
 * Spec: docs/superpowers/specs/2026-05-10-supplier-integration-design.md §2.2
 *
 * @mixin IdeHelperSupplierProject
 */
class SupplierProject extends Model
{
    /** @use HasFactory<SupplierProjectFactory> */
    use HasFactory;

    protected $table = 'supplier_projects';

    protected $fillable = [
        'platform',
        'signal_type',
        'unique_key',
        'supplier_external_id',
        'current_limit',
        'current_workdays',
        'current_regions',
        'sync_status',
        'last_synced_at',
        'inactive_since',
        'subject_code',
    ];

    protected function casts(): array
    {
        return [
            'current_workdays' => 'array',
            'current_regions' => 'array',
            'current_limit' => 'integer',
            'last_synced_at' => 'datetime',
            'inactive_since' => 'datetime',
            'subject_code' => 'integer',
        ];
    }

    /**
     * @param  Builder<SupplierProject>  $query
     * @return Builder<SupplierProject>
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->whereNull('inactive_since');
    }

    /**
     * @param  Builder<SupplierProject>  $query
     * @return Builder<SupplierProject>
     */
    public function scopeStaleSince(Builder $query, int $days): Builder
    {
        return $query->whereNotNull('inactive_since')
            ->where('inactive_since', '<=', now()->subDays($days));
    }

    /**
     * @param  Builder<SupplierProject>  $query
     * @return Builder<SupplierProject>
     */
    public function scopeForSignal(Builder $query, string $signalType, string $uniqueKey): Builder
    {
        return $query->where('signal_type', $signalType)->where('unique_key', $uniqueKey);
    }

    /**
     * @return BelongsToMany<Project, $this>
     */
    public function projects(): BelongsToMany
    {
        return $this->belongsToMany(Project::class, 'project_supplier_links')
            ->withPivot(['platform', 'subject_code']);
    }

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