<?php

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

use App\Http\Controllers\Controller;
use App\Services\AgentSettlement\SettlementCenterLedgerService;
use App\Services\AgentSettlement\SettlementLedgerListFilters;
use App\Support\AdminAgentSettlementScope;
use App\Support\ApiResponse;
use App\Support\PaginationTrait;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 结算中心：信用盘玩家实时流水（{@see credit_ledger}），与关账后 {@see settlement_bills} 不同。
 */
final class AdminCreditLedgerIndexController extends Controller
{
    use PaginationTrait;

    public function __construct(
        private readonly SettlementCenterLedgerService $ledgerService,
    ) {}

    public function __invoke(Request $request): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $adminSiteId = (int) $request->query('admin_site_id', 0);
        abort_if($adminSiteId <= 0, 422, 'admin.admin_site_id_required');
        abort_if(! AdminAgentSettlementScope::siteAccessible($admin, $adminSiteId), 403);

        $siteCode = (string) DB::table('admin_sites')->where('id', $adminSiteId)->value('code');
        abort_if($siteCode === '', 422, 'admin.admin_site_not_found');

        $periodId = (int) $request->query('settlement_period_id', 0);
        if ($periodId > 0) {
            abort_if(! AdminAgentSettlementScope::periodAccessible($admin, $periodId), 403);
        }

        $filters = SettlementLedgerListFilters::fromQuery(array_merge(
            $request->query(),
            $periodId > 0 ? ['settlement_period_id' => $periodId] : [],
        ));

        $perPage = $this->perPage($request, 'per_page', 20, 100);
        $page = $this->page($request);

        $result = $filters->betFlowDisplaySimple
            ? $this->ledgerService->listBetFlowSimplified($admin, $siteCode, $page, $perPage, $filters)
            : $this->ledgerService->listUnified($admin, $siteCode, $page, $perPage, $filters);

        return ApiResponse::success($result);
    }
}
