<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Services\AuditService;
use App\Services\CustomerRiskService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\View;

class CreditScoreController extends Controller
{
    public function history(Request $request, Customer $customer): View
    {
        Gate::authorize('view', $customer);

        $customer->load(['branch', 'riskProfile']);
        $histories = $customer->creditScoreHistories()
            ->with('creator')
            ->latest('calculated_at')
            ->latest('id')
            ->paginate(25);

        return view('credit-score.history', compact('customer', 'histories'));
    }

    public function recalculate(Request $request, Customer $customer, CustomerRiskService $risk): RedirectResponse
    {
        Gate::authorize('view', $customer);

        $before = $customer->riskProfile()->first()?->toArray() ?? [];
        $snapshot = $risk->refreshWithHistory($customer->fresh(), 'manual_recalculation');

        AuditService::record(
            'credit_score.recalculated',
            $customer,
            $before,
            [
                'history_id' => $snapshot->id,
                'score' => $snapshot->score,
                'score_band' => $snapshot->score_band,
                'risk_level' => $snapshot->risk_level,
                'confidence' => $snapshot->confidence,
                'thin_file' => $snapshot->thin_file,
                'manual_review_required' => $snapshot->manual_review_required,
                'score_version' => $snapshot->score_version,
            ],
            $customer->branch_id,
        );

        return back()->with('success', 'Credit score recalculated.');
    }
}
