<?php

namespace App\Http\Controllers\Api\V1\Admin\AgentSettlement;

use App\Http\Controllers\Controller;
use App\Http\Middleware\RecordAdminApiAudit;
use App\Services\AgentSettlement\SettlementPaymentService;
use App\Services\AuditLogger;
use App\Support\AdminAgentSettlementScope;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

final class AgentSettlementBillConfirmController extends Controller
{
    public function __invoke(
        Request $request,
        int $settlement_bill,
        SettlementPaymentService $payments,
    ): JsonResponse {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        AdminAgentSettlementScope::assertCanOperateBill($admin, $settlement_bill);

        $bill = DB::table('settlement_bills')->where('id', $settlement_bill)->first();
        abort_if($bill === null, 404);

        $payments->confirmBill($settlement_bill);

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            moduleCode: 'settlement',
            actionCode: 'settlement_bill.confirm',
            targetType: 'settlement_bill',
            targetId: (string) $settlement_bill,
            beforeJson: ['status' => (string) $bill->status],
            afterJson: ['status' => 'confirmed'],
        );
        $request->attributes->set(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED, true);

        return ApiResponse::success(['bill_id' => $settlement_bill, 'status' => 'confirmed']);
    }
}
