import { apiRequest } from "@/shared/api/request";
import { API_ENDPOINTS, API_OPERATIONS, apiEndpointPath } from "@/shared/api/generated/endpoints";

export interface LuckyGiftTierDto {
    tierId: string;
    multiplier: number;
    probabilityPercent: number;
    rewardSource: string;
    highWaterOnly: boolean;
    broadcastLevel: string;
    enabled: boolean;
}

export interface LuckyGiftStageDto {
    stage: string;
    tiers: LuckyGiftTierDto[];
}

export interface LuckyGiftConfigDto {
    appCode?: string;
    poolId: string;
    enabled: boolean;
    ruleVersion: number;
    targetRTPPercent: number;
    poolRatePercent: number;
    settlementWindowWager: number;
    controlBandPercent: number;
    giftPriceReference: number;
    noviceMaxEquivalentDraws: number;
    normalMaxEquivalentDraws: number;
    maxSinglePayout: number;
    userHourlyPayoutCap: number;
    userDailyPayoutCap: number;
    deviceDailyPayoutCap: number;
    roomHourlyPayoutCap: number;
    anchorDailyPayoutCap: number;
    effectiveFromMs: number;
    createdByAdminId?: number;
    createdAtMs?: number;
    stages: LuckyGiftStageDto[];
}

export interface LuckyGiftConfigPayload {
    pool_id: string;
    enabled: boolean;
    target_rtp_percent: number;
    pool_rate_percent: number;
    settlement_window_wager: number;
    control_band_percent: number;
    gift_price_reference: number;
    novice_max_equivalent_draws: number;
    normal_max_equivalent_draws: number;
    max_single_payout: number;
    user_hourly_payout_cap: number;
    user_daily_payout_cap: number;
    device_daily_payout_cap: number;
    room_hourly_payout_cap: number;
    anchor_daily_payout_cap: number;
    effective_from_ms: number;
    stages: Array<{
        stage: string;
        tiers: Array<{
            tier_id: string;
            multiplier: number;
            probability_percent: number;
            reward_source: string;
            high_water_only: boolean;
            broadcast_level: string;
            enabled: boolean;
        }>;
    }>;
}

export interface LuckyGiftDrawSummaryDto {
    poolId: string;
    totalDraws: number;
    uniqueUsers: number;
    uniqueRooms: number;
    totalSpentCoins: number;
    totalRewardCoins: number;
    baseRewardCoins: number;
    roomAtmosphereRewardCoins: number;
    activitySubsidyCoins: number;
    actualRTPPPM: number;
    pendingDraws: number;
    grantedDraws: number;
    failedDraws: number;
}

type RawConfig = LuckyGiftConfigDto & Record<string, unknown>;
type RawStage = LuckyGiftStageDto & Record<string, unknown>;
type RawTier = LuckyGiftTierDto & Record<string, unknown>;
type RawSummary = LuckyGiftDrawSummaryDto & Record<string, unknown>;
type LuckyGiftDrawSummaryQuery = Record<string, number | string | undefined>;

export function getLuckyGiftConfig(poolId: string): Promise<LuckyGiftConfigDto> {
    const endpoint = API_ENDPOINTS.getLuckyGiftConfig;
    return apiRequest<RawConfig>(apiEndpointPath(API_OPERATIONS.getLuckyGiftConfig), {
        method: endpoint.method,
        query: { pool_id: poolId },
    }).then(normalizeConfig);
}

export function listLuckyGiftConfigs(): Promise<LuckyGiftConfigDto[]> {
    const endpoint = API_ENDPOINTS.listLuckyGiftConfigs;
    return apiRequest<RawConfig[]>(apiEndpointPath(API_OPERATIONS.listLuckyGiftConfigs), {
        method: endpoint.method,
    }).then((items) => (items || []).map(normalizeConfig));
}

export function updateLuckyGiftConfig(payload: LuckyGiftConfigPayload): Promise<LuckyGiftConfigDto> {
    const endpoint = API_ENDPOINTS.upsertLuckyGiftConfig;
    return apiRequest<RawConfig, LuckyGiftConfigPayload>(apiEndpointPath(API_OPERATIONS.upsertLuckyGiftConfig), {
        body: payload,
        method: endpoint.method,
        query: { pool_id: payload.pool_id },
    }).then(normalizeConfig);
}

export function getLuckyGiftDrawSummary(query: LuckyGiftDrawSummaryQuery = {}): Promise<LuckyGiftDrawSummaryDto> {
    const endpoint = API_ENDPOINTS.getLuckyGiftDrawSummary;
    return apiRequest<RawSummary>(apiEndpointPath(API_OPERATIONS.getLuckyGiftDrawSummary), {
        method: endpoint.method,
        query,
    }).then(normalizeSummary);
}

function normalizeConfig(item: RawConfig): LuckyGiftConfigDto {
    // admin-server 已经把内部 ppm 转回业务单位；前端只接受 percent/multiplier 字段，
    // 这样页面展示、表单校验和提交 payload 使用同一套单位。
    return {
        appCode: stringValue(item.appCode ?? item.app_code),
        createdAtMs: numberValue(item.createdAtMs ?? item.created_at_ms),
        createdByAdminId: numberValue(item.createdByAdminId ?? item.created_by_admin_id),
        effectiveFromMs: numberValue(item.effectiveFromMs ?? item.effective_from_ms),
        enabled: booleanValue(item.enabled),
        giftPriceReference: numberValue(item.giftPriceReference ?? item.gift_price_reference),
        noviceMaxEquivalentDraws: numberValue(item.noviceMaxEquivalentDraws ?? item.novice_max_equivalent_draws),
        normalMaxEquivalentDraws: numberValue(item.normalMaxEquivalentDraws ?? item.normal_max_equivalent_draws),
        maxSinglePayout: numberValue(item.maxSinglePayout ?? item.max_single_payout),
        userHourlyPayoutCap: numberValue(item.userHourlyPayoutCap ?? item.user_hourly_payout_cap),
        userDailyPayoutCap: numberValue(item.userDailyPayoutCap ?? item.user_daily_payout_cap),
        deviceDailyPayoutCap: numberValue(item.deviceDailyPayoutCap ?? item.device_daily_payout_cap),
        roomHourlyPayoutCap: numberValue(item.roomHourlyPayoutCap ?? item.room_hourly_payout_cap),
        anchorDailyPayoutCap: numberValue(item.anchorDailyPayoutCap ?? item.anchor_daily_payout_cap),
        poolId: stringValue(item.poolId ?? item.pool_id),
        poolRatePercent: numberValue(item.poolRatePercent ?? item.pool_rate_percent),
        ruleVersion: numberValue(item.ruleVersion ?? item.rule_version),
        settlementWindowWager: numberValue(item.settlementWindowWager ?? item.settlement_window_wager),
        stages: arrayValue(item.stages).map(normalizeStage),
        targetRTPPercent: numberValue(item.targetRTPPercent ?? item.target_rtp_percent),
        controlBandPercent: numberValue(item.controlBandPercent ?? item.control_band_percent),
    };
}

function normalizeStage(raw: unknown): LuckyGiftStageDto {
    const item = asRecord(raw) as RawStage;
    return {
        stage: stringValue(item.stage),
        tiers: arrayValue(item.tiers).map(normalizeTier),
    };
}

function normalizeTier(raw: unknown): LuckyGiftTierDto {
    const item = asRecord(raw) as RawTier;
    // 奖档概率是发布配置的一部分，不再使用旧 weight=0 的运行时自动权重模型。
    return {
        broadcastLevel: stringValue(item.broadcastLevel ?? item.broadcast_level),
        enabled: booleanValue(item.enabled),
        highWaterOnly: booleanValue(item.highWaterOnly ?? item.high_water_only),
        multiplier: numberValue(item.multiplier),
        probabilityPercent: numberValue(item.probabilityPercent ?? item.probability_percent),
        rewardSource: stringValue(item.rewardSource ?? item.reward_source),
        tierId: stringValue(item.tierId ?? item.tier_id),
    };
}

function normalizeSummary(item: RawSummary): LuckyGiftDrawSummaryDto {
    return {
        poolId: stringValue(item.poolId ?? item.pool_id),
        totalDraws: numberValue(item.totalDraws ?? item.total_draws),
        uniqueUsers: numberValue(item.uniqueUsers ?? item.unique_users),
        uniqueRooms: numberValue(item.uniqueRooms ?? item.unique_rooms),
        totalSpentCoins: numberValue(item.totalSpentCoins ?? item.total_spent_coins),
        totalRewardCoins: numberValue(item.totalRewardCoins ?? item.total_reward_coins),
        baseRewardCoins: numberValue(item.baseRewardCoins ?? item.base_reward_coins),
        roomAtmosphereRewardCoins: numberValue(item.roomAtmosphereRewardCoins ?? item.room_atmosphere_reward_coins),
        activitySubsidyCoins: numberValue(item.activitySubsidyCoins ?? item.activity_subsidy_coins),
        actualRTPPPM: numberValue(item.actualRTPPPM ?? item.actual_rtp_ppm),
        pendingDraws: numberValue(item.pendingDraws ?? item.pending_draws),
        grantedDraws: numberValue(item.grantedDraws ?? item.granted_draws),
        failedDraws: numberValue(item.failedDraws ?? item.failed_draws),
    };
}

function asRecord(value: unknown): Record<string, unknown> {
    return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
}

function arrayValue(value: unknown): unknown[] {
    return Array.isArray(value) ? value : [];
}

function booleanValue(value: unknown) {
    return value === true || value === "true" || value === 1 || value === "1";
}

function stringValue(value: unknown) {
    return typeof value === "string" ? value : value === undefined || value === null ? "" : String(value);
}

function numberValue(value: unknown) {
    const number = Number(value || 0);
    return Number.isFinite(number) ? number : 0;
}
