<?php

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

use App\Models\Player;
use App\Models\TicketOrder;
use App\Lottery\ErrorCode;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\AdminSiteScope;
use App\Support\PlayerFundingMode;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

/** DELETE /api/v1/admin/players/{player} */
final class AdminPlayerDestroyController extends Controller
{
    public function __invoke(Request $request, Player $player): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        if ($denied = AdminSiteScope::denyUnlessPlayerAccessible($admin, $player)) {
            return $denied;
        }

        if (PlayerFundingMode::usesCredit($player)) {
            $creditRow = DB::table('player_credit_accounts')
                ->where('player_id', $player->getKey())
                ->first();

            $usedCredit = (int) ($creditRow->used_credit ?? 0);
            $frozenCredit = (int) ($creditRow->frozen_credit ?? 0);
            if ($usedCredit !== 0 || $frozenCredit !== 0) {
                return ApiMessage::errorResponse($request, 'admin.player_credit_in_use_blocks_delete', ErrorCode::ValidationFailed->value, null, 422);
            }
        } else {
            $hasWallets = Player::query()
                ->whereKey($player->getKey())
                ->whereHas('wallets', static fn (Builder $q) => $q->where('balance', '!=', 0))
                ->exists();

            if ($hasWallets) {
                return ApiMessage::errorResponse($request, 'admin.player_wallet_balance_blocks_delete', ErrorCode::ValidationFailed->value, null, 422);
            }
        }

        $hasUnpaidSettlementBills = DB::table('settlement_bills')
            ->where('owner_type', 'player')
            ->where('owner_id', $player->getKey())
            ->whereIn('status', ['confirmed', 'partial_paid', 'overdue'])
            ->where('unpaid_amount', '>', 0)
            ->exists();

        if ($hasUnpaidSettlementBills) {
            return ApiMessage::errorResponse($request, 'admin.player_unpaid_settlement_blocks_delete', ErrorCode::ValidationFailed->value, null, 422);
        }

        $hasTickets = TicketOrder::query()
            ->where('player_id', $player->getKey())
            ->exists();

        if ($hasTickets) {
            return ApiMessage::errorResponse($request, 'admin.player_has_tickets_blocks_delete', ErrorCode::ValidationFailed->value, null, 422);
        }

        DB::table('player_credit_accounts')->where('player_id', $player->getKey())->delete();
        $player->wallets()->delete();
        $player->delete();

        return ApiResponse::success(['deleted' => true]);
    }
}
