<?php

namespace App\Http\Controllers\Web\Bo;

use App\Http\Controllers\Controller;
use App\Jobs\ProcessPayoutRequest;
use App\Models\Payout;
use App\Services\AdminAuditLogger;
use App\Services\Payments\PayoutProcessor;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class FinancePayoutController extends Controller
{
    public function process(Request $request, Payout $payout, AdminAuditLogger $auditLogger): RedirectResponse
    {
        ProcessPayoutRequest::dispatch($payout->id);

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

        return back()->with('status', sprintf('Traitement du retrait #%d lance.', $payout->id));
    }

    public function markPaid(
        Request $request,
        Payout $payout,
        PayoutProcessor $processor,
        AdminAuditLogger $auditLogger,
    ): RedirectResponse {
        $processor->markPayoutPaid($payout, metadata: [
            'manual_admin_validation' => true,
        ]);

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

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

    public function markFailed(
        Request $request,
        Payout $payout,
        PayoutProcessor $processor,
        AdminAuditLogger $auditLogger,
    ): RedirectResponse {
        $data = $request->validate([
            'reason' => ['required', 'string', 'max:255'],
        ]);

        $processor->markPayoutFailed($payout, $data['reason'], metadata: [
            'manual_admin_reject' => true,
        ]);

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

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