<?php

namespace App\Http\Controllers\Web\Bo;

use App\Http\Controllers\Controller;
use App\Jobs\ProcessMissionSettlementPayment;
use App\Models\Payment;
use App\Services\AdminAuditLogger;
use App\Services\Payments\MissionSettlementProcessor;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class FinancePaymentController extends Controller
{
    public function retry(Request $request, Payment $payment, AdminAuditLogger $auditLogger): RedirectResponse
    {
        if (!$payment->mission_id) {
            return back()->with('status', 'Impossible de relancer un paiement sans mission associee.');
        }

        ProcessMissionSettlementPayment::dispatch($payment->mission_id);

        $auditLogger->log(
            admin: $request->user(),
            action: 'bo.finance.payment.retry',
            auditable: $payment,
            metadata: [
                'mission_id' => $payment->mission_id,
            ],
        );

        return back()->with('status', sprintf('Relance du paiement #%d en queue.', $payment->id));
    }

    public function markPaid(
        Request $request,
        Payment $payment,
        MissionSettlementProcessor $processor,
        AdminAuditLogger $auditLogger,
    ): RedirectResponse {
        $processor->markPaymentPaid($payment);

        $auditLogger->log(
            admin: $request->user(),
            action: 'bo.finance.payment.mark_paid',
            auditable: $payment,
            metadata: [
                'payment_id' => $payment->id,
            ],
        );

        return back()->with('status', sprintf('Paiement #%d marque comme paye.', $payment->id));
    }

    public function markFailed(Request $request, Payment $payment, AdminAuditLogger $auditLogger): RedirectResponse
    {
        $data = $request->validate([
            'reason' => ['nullable', 'string', 'max:255'],
        ]);

        $payment->update([
            'status' => 'failed',
            'failure_reason' => $data['reason'] ?? 'Echec defini par l administrateur',
        ]);

        $auditLogger->log(
            admin: $request->user(),
            action: 'bo.finance.payment.mark_failed',
            auditable: $payment,
            metadata: [
                'payment_id' => $payment->id,
                'reason' => $data['reason'] ?? null,
            ],
        );

        return back()->with('status', sprintf('Paiement #%d marque comme echec.', $payment->id));
    }
}
