<?php

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

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

final class AgentSettlementBillBadDebtWriteOffController extends Controller
{
    public function __invoke(
        AdminSettlementBillBadDebtRequest $request,
        int $settlement_bill,
        AgentSettlementBadDebtService $badDebt,
    ): JsonResponse {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);
        abort_if(! AdminAgentSettlementScope::billAccessible($admin, $settlement_bill), 404);
        AdminAgentSettlementScope::assertCanPerformFinanceAdjustments($admin);

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

        $archiveBillId = $badDebt->writeOff(
            $settlement_bill,
            $request->validated('reason'),
            (int) $admin->id,
            $request->validated('idempotency_key'),
        );

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

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

        return ApiResponse::success([
            'original_bill_id' => $settlement_bill,
            'bad_debt_bill_id' => $archiveBillId,
            'bill' => $after,
        ]);
    }
}
