<?php

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

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

final class AgentSettlementBillAdjustmentController extends Controller
{
    public function __invoke(
        AdminSettlementBillAdjustmentRequest $request,
        int $settlement_bill,
        AgentSettlementBillAdjustmentService $adjustments,
    ): 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);

        $newBillId = $adjustments->createAdjustment(
            $settlement_bill,
            (int) $request->validated('amount'),
            (string) ($request->validated('adjustment_type') ?? 'adjustment'),
            $request->validated('reason'),
            (int) $admin->id,
            $request->validated('idempotency_key'),
        );

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

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

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