<?php

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

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

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

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

        $validated = $request->validated();
        $payments->recordPayment(
            $settlement_bill,
            (int) $validated['amount'],
            (int) $admin->id,
            [
                'method' => $validated['method'] ?? null,
                'proof' => $validated['proof'] ?? null,
                'remark' => $validated['remark'] ?? null,
                'idempotency_key' => $validated['idempotency_key'] ?? null,
            ],
        );

        $after = DB::table('settlement_bills')->where('id', $settlement_bill)->first();

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            moduleCode: 'settlement',
            actionCode: 'settlement_bill.payment',
            targetType: 'settlement_bill',
            targetId: (string) $settlement_bill,
            beforeJson: (array) $before,
            afterJson: (array) $after,
        );
        $request->attributes->set(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED, true);

        return ApiResponse::success(['bill' => $after]);
    }
}
