<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class TrustScore extends Model
{
    use HasFactory;

    protected $fillable = [
        'media_owner_id',
        'placement_id',
        'score',
        'proof_timeliness_score',
        'proof_pass_rate_score',
        'dispute_score',
        'cancellation_score',
        'total_bookings',
        'proof_on_time',
        'proof_late',
        'proof_missed',
        'proof_passed',
        'proof_failed',
        'disputes_raised',
        'disputes_lost',
        'cancellations',
        'instant_book_eligible',
        'last_evaluated_at',
    ];

    protected $casts = [
        'score'                  => 'decimal:2',
        'proof_timeliness_score' => 'decimal:2',
        'proof_pass_rate_score'  => 'decimal:2',
        'dispute_score'          => 'decimal:2',
        'cancellation_score'     => 'decimal:2',
        'instant_book_eligible'  => 'boolean',
        'last_evaluated_at'      => 'datetime',
    ];

    // ============================================================
    // Scopes
    // ============================================================
    public function scopeInstantBookEligible($query)
    {
        return $query->where('instant_book_eligible', true);
    }

    public function scopeOwnerLevel($query)
    {
        return $query->whereNull('placement_id');
    }

    public function scopePlacementLevel($query)
    {
        return $query->whereNotNull('placement_id');
    }

    // ============================================================
    // Helpers
    // ============================================================
    public function getBadge(): string
    {
        if ($this->score >= 4.5) return 'Excellent';
        if ($this->score >= 3.5) return 'Good';
        if ($this->score >= 2.5) return 'Fair';
        return 'Poor';
    }

    public function getBadgeClass(): string
    {
        if ($this->score >= 4.5) return 'nx-badge-good';
        if ($this->score >= 3.5) return 'nx-badge-accent';
        if ($this->score >= 2.5) return 'nx-badge-warn';
        return 'nx-badge-danger';
    }

    public function getProofPassRate(): float
    {
        $total = $this->proof_passed + $this->proof_failed;
        if ($total === 0) return 0;
        return round(($this->proof_passed / $total) * 100, 1);
    }

    public function getProofTimelinessRate(): float
    {
        $total = $this->proof_on_time + $this->proof_late + $this->proof_missed;
        if ($total === 0) return 0;
        return round(($this->proof_on_time / $total) * 100, 1);
    }

    public function getDisputeWinRate(): float
    {
        if ($this->disputes_raised === 0) return 100;
        $won = $this->disputes_raised - $this->disputes_lost;
        return round(($won / $this->disputes_raised) * 100, 1);
    }

    public function recalculate(): void
    {
        // Weighted scoring
        $proofTimeliness = $this->getProofTimelinessRate() / 100;
        $proofPassRate   = $this->getProofPassRate() / 100;
        $disputeRate     = $this->disputes_raised > 0
            ? 1 - ($this->disputes_lost / $this->disputes_raised)
            : 1;
        $cancellationRate = $this->total_bookings > 0
            ? 1 - ($this->cancellations / $this->total_bookings)
            : 1;

        // Weights: proof timeliness 30%, pass rate 30%, disputes 25%, cancellations 15%
        $score = (
            ($proofTimeliness * 0.30) +
            ($proofPassRate   * 0.30) +
            ($disputeRate     * 0.25) +
            ($cancellationRate* 0.15)
        ) * 5;

        $eligible = $score >= 4.0
            && $this->getProofPassRate() >= 90
            && $this->getProofTimelinessRate() >= 90;

        $this->update([
            'score'                  => round($score, 2),
            'proof_timeliness_score' => round($proofTimeliness * 5, 2),
            'proof_pass_rate_score'  => round($proofPassRate * 5, 2),
            'dispute_score'          => round($disputeRate * 5, 2),
            'cancellation_score'     => round($cancellationRate * 5, 2),
            'instant_book_eligible'  => $eligible,
            'last_evaluated_at'      => now(),
        ]);
    }

    // ============================================================
    // Relationships
    // ============================================================
    public function mediaOwner()
    {
        return $this->belongsTo(MediaOwner::class);
    }

    public function placement()
    {
        return $this->belongsTo(Placement::class);
    }
}