<?php

namespace App\Services;

use App\Models\Customer;
use App\Models\CustomerRating;
use App\Models\CustomerViolation;
use App\Models\PaymentDelay;
use App\Models\Blacklist;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class CustomerRiskService
{
    public function registerViolation(Customer $customer, array $violationData)
    {
        return DB::transaction(function () use ($customer, $violationData) {
            $violation = $customer->violations()->create($violationData);

            $rating = $customer->rating ?? $customer->createRating();
            $rating->increment('violation_count');
            $rating->update(['last_violation_date' => now()]);

            $rating->updateRiskLevel();

            if ($rating->risk_level === 'critical') {
                $this->considerAutoBlacklist($customer, 'violations', 'عدد مخالفات عالي جداً', $violation->id);
            }

            return $violation;
        });
    }

    public function registerPaymentDelay(Customer $customer, array $delayData)
    {
        return DB::transaction(function () use ($customer, $delayData) {
            $delay = $customer->paymentDelays()->create($delayData);

            $rating = $customer->rating ?? $customer->createRating();
            $rating->increment('late_payment_count');
            $rating->increment('total_late_amount', $delayData['delayed_amount']);
            $rating->update(['last_late_payment_date' => now()]);

            $rating->updateRiskLevel();

            if ($rating->risk_level === 'critical') {
                $this->considerAutoBlacklist($customer, 'non_payment', 'تأخير سداد مستمر', $delay->id);
            }

            return $delay;
        });
    }

    public function addToBlacklist(Customer $customer, string $reason, string $description, int $blacklistedBy, ?int $days = null)
    {
        return DB::transaction(function () use ($customer, $reason, $description, $blacklistedBy, $days) {
            $blacklist = $customer->blacklistEntries()->create([
                'reason' => $reason,
                'description' => $description,
                'blacklisted_from' => now(),
                'blacklisted_until' => $days ? now()->addDays($days) : null,
                'status' => 'active',
                'blacklisted_by' => $blacklistedBy,
            ]);

            $rating = $customer->rating ?? $customer->createRating();
            $rating->update(['status' => 'blacklisted']);

            return $blacklist;
        });
    }

    public function removeFromBlacklist(Blacklist $blacklist, int $liftedBy, string $reason)
    {
        return $blacklist->lift($liftedBy, $reason);
    }

    public function calculateRiskScore(Customer $customer)
    {
        $rating = $customer->rating;
        if (!$rating) {
            return 0;
        }

        $score = 0;

        if ($rating->violation_count >= 5) $score += 40;
        elseif ($rating->violation_count >= 3) $score += 20;
        elseif ($rating->violation_count > 0) $score += 10;

        if ($rating->late_payment_count >= 3) $score += 40;
        elseif ($rating->late_payment_count >= 1) $score += 20;

        if ($rating->total_late_amount > 10000) $score += 30;
        elseif ($rating->total_late_amount > 5000) $score += 15;

        if ($customer->isBlacklisted()) {
            $score += 50;
        }

        return $score;
    }

    public function getRiskStatus(Customer $customer)
    {
        if ($customer->isBlacklisted()) {
            return [
                'level' => 'blacklisted',
                'label' => app()->getLocale() == 'ar' ? 'محظور' : 'Blacklisted',
                'color' => 'danger',
                'icon' => '🚫'
            ];
        }

        $rating = $customer->rating;
        if (!$rating) {
            return [
                'level' => 'unknown',
                'label' => app()->getLocale() == 'ar' ? 'غير معروف' : 'Unknown',
                'color' => 'secondary',
                'icon' => '❓'
            ];
        }

        $riskMap = [
            'critical' => [
                'label' => app()->getLocale() == 'ar' ? 'حرج جداً' : 'Critical',
                'color' => 'danger',
                'icon' => '🔴'
            ],
            'high' => [
                'label' => app()->getLocale() == 'ar' ? 'مرتفع' : 'High',
                'color' => 'warning',
                'icon' => '🟠'
            ],
            'medium' => [
                'label' => app()->getLocale() == 'ar' ? 'متوسط' : 'Medium',
                'color' => 'info',
                'icon' => '🟡'
            ],
            'low' => [
                'label' => app()->getLocale() == 'ar' ? 'منخفض' : 'Low',
                'color' => 'success',
                'icon' => '🟢'
            ]
        ];

        return array_merge(['level' => $rating->risk_level], $riskMap[$rating->risk_level] ?? []);
    }

    private function considerAutoBlacklist(Customer $customer, string $reason, string $description, int $refId)
    {
        $rating = $customer->rating;

        if ($reason === 'violations' && $rating->violation_count >= 7) {
            $this->addToBlacklist($customer, 'violations', $description, auth()->id(), 30);
        } elseif ($reason === 'non_payment' && $rating->late_payment_count >= 4) {
            $this->addToBlacklist($customer, 'non_payment', $description, auth()->id(), 60);
        }
    }
}
