<?php

namespace App\Models;

use App\Models\Scopes\BranchScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use LogicException;

class CustomerCreditScoreHistory extends Model
{
    protected $fillable = [
        'customer_id',
        'branch_id',
        'score',
        'score_band',
        'risk_level',
        'confidence',
        'thin_file',
        'manual_review_required',
        'score_version',
        'trigger',
        'component_scores',
        'factors',
        'explanation',
        'calculated_at',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'score' => 'decimal:2',
            'confidence' => 'decimal:2',
            'thin_file' => 'boolean',
            'manual_review_required' => 'boolean',
            'component_scores' => 'array',
            'factors' => 'array',
            'calculated_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::addGlobalScope(new BranchScope);

        static::updating(function (): void {
            throw new LogicException('Credit score history snapshots are immutable.');
        });

        static::deleting(function (): void {
            throw new LogicException('Credit score history snapshots are immutable.');
        });
    }

    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

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