<?php

namespace App\Http\Controllers\Web\Bo;

use App\Http\Controllers\Controller;
use App\Models\PaymentGatewaySetting;
use App\Services\AdminAuditLogger;
use App\Services\PaymentGatewayConfigService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class FinanceGatewaySettingsController extends Controller
{
    public function update(
        Request $request,
        PaymentGatewayConfigService $paymentGatewayConfigService,
        AdminAuditLogger $adminAuditLogger,
    ): RedirectResponse {
        $admin = $request->user();
        abort_unless($admin !== null && $admin->isAdmin(), 403);

        $paymentGatewayConfigService->saveFromBo([], $admin->id);

        $paymentGatewayConfigService->applyRuntimeOverrides();
        Artisan::call('queue:restart');

        $simulateFromEnv = (bool) config('lineup.payments.simulate', true);

        $auditable = PaymentGatewaySetting::query()
            ->where('gateway', 'global')
            ->first() ?? $admin;

        $adminAuditLogger->log(
            admin: $admin,
            action: 'bo.finance.gateway_settings.update',
            auditable: $auditable,
            metadata: [
                'simulate_from_env' => $simulateFromEnv,
                'gateways_forced_from_env' => true,
            ],
        );

        return redirect()
            ->route('bo.finance')
            ->with('status', 'Configuration Stripe/PayPal/simulate forcee depuis .env (lecture seule dans le BO).');
    }
}
