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

export interface CumulativeRechargeRewardTierDto {
    tierId: number;
    tierCode: string;
    tierName: string;
    thresholdUsdMinor: number;
    resourceGroupId: number;
    status: string;
    sortOrder: number;
    createdAtMs?: number;
    updatedAtMs?: number;
}

export interface CumulativeRechargeRewardConfigDto {
    appCode?: string;
    enabled: boolean;
    tiers: CumulativeRechargeRewardTierDto[];
    updatedByAdminId?: number;
    createdAtMs?: number;
    updatedAtMs?: number;
}

export interface CumulativeRechargeRewardConfigPayload {
    enabled: boolean;
    tiers: Array<{
        tier_id?: number;
        tier_code: string;
        tier_name: string;
        threshold_usd_minor: number;
        resource_group_id: number;
        status: string;
        sort_order: number;
    }>;
}

export interface CumulativeRechargeRewardGrantUserDto {
    userId?: string;
    displayUserId?: string;
    prettyDisplayUserId?: string;
    prettyId?: string;
    username?: string;
    avatar?: string;
}

export interface CumulativeRechargeRewardGrantDto {
    grantId: string;
    appCode?: string;
    cycleKey?: string;
    eventId?: string;
    transactionId?: string;
    commandId?: string;
    userId: string;
    user?: CumulativeRechargeRewardGrantUserDto;
    tierId?: number;
    tierCode?: string;
    resourceGroupId?: number;
    thresholdUsdMinor?: number;
    reachedUsdMinor?: number;
    qualifyingUsdMinor?: number;
    rechargeCoinAmount?: number;
    rechargeType?: string;
    status?: string;
    walletCommandId?: string;
    walletGrantId?: string;
    failureReason?: string;
    grantedAtMs?: number;
    createdAtMs?: number;
    updatedAtMs?: number;
}

type RawConfig = CumulativeRechargeRewardConfigDto & Record<string, unknown>;
type RawTier = CumulativeRechargeRewardTierDto & Record<string, unknown>;
type RawGrant = CumulativeRechargeRewardGrantDto & Record<string, unknown>;

export function getCumulativeRechargeRewardConfig(): Promise<CumulativeRechargeRewardConfigDto> {
    const endpoint = API_ENDPOINTS.getCumulativeRechargeRewardConfig;
    return apiRequest<RawConfig>(apiEndpointPath(API_OPERATIONS.getCumulativeRechargeRewardConfig), {
        method: endpoint.method,
    }).then(normalizeConfig);
}

export function updateCumulativeRechargeRewardConfig(
    payload: CumulativeRechargeRewardConfigPayload,
): Promise<CumulativeRechargeRewardConfigDto> {
    const endpoint = API_ENDPOINTS.updateCumulativeRechargeRewardConfig;
    return apiRequest<RawConfig, CumulativeRechargeRewardConfigPayload>(
        apiEndpointPath(API_OPERATIONS.updateCumulativeRechargeRewardConfig),
        {
            body: payload,
            method: endpoint.method,
        },
    ).then(normalizeConfig);
}

export function listCumulativeRechargeRewardGrants(
    query: PageQuery = {},
): Promise<ApiPage<CumulativeRechargeRewardGrantDto>> {
    const endpoint = API_ENDPOINTS.listCumulativeRechargeRewardGrants;
    return apiRequest<ApiPage<RawGrant>>(apiEndpointPath(API_OPERATIONS.listCumulativeRechargeRewardGrants), {
        method: endpoint.method,
        query,
    }).then((page) => ({
        ...page,
        items: (page.items || []).map(normalizeGrant),
    }));
}

function normalizeConfig(item: RawConfig): CumulativeRechargeRewardConfigDto {
    const rawTiers = Array.isArray(item.tiers) ? (item.tiers as RawTier[]) : [];
    return {
        appCode: stringValue(item.appCode ?? item.app_code),
        enabled: Boolean(item.enabled),
        tiers: rawTiers.map(normalizeTier),
        updatedByAdminId: numberValue(item.updatedByAdminId ?? item.updated_by_admin_id),
        createdAtMs: numberValue(item.createdAtMs ?? item.created_at_ms),
        updatedAtMs: numberValue(item.updatedAtMs ?? item.updated_at_ms),
    };
}

function normalizeTier(item: RawTier): CumulativeRechargeRewardTierDto {
    return {
        tierId: numberValue(item.tierId ?? item.tier_id),
        tierCode: stringValue(item.tierCode ?? item.tier_code),
        tierName: stringValue(item.tierName ?? item.tier_name),
        thresholdUsdMinor: numberValue(item.thresholdUsdMinor ?? item.threshold_usd_minor),
        resourceGroupId: numberValue(item.resourceGroupId ?? item.resource_group_id),
        status: stringValue(item.status) || "active",
        sortOrder: numberValue(item.sortOrder ?? item.sort_order),
        createdAtMs: numberValue(item.createdAtMs ?? item.created_at_ms),
        updatedAtMs: numberValue(item.updatedAtMs ?? item.updated_at_ms),
    };
}

function normalizeGrant(item: RawGrant): CumulativeRechargeRewardGrantDto {
    const rawUser = (item.user || {}) as Record<string, unknown>;
    return {
        grantId: stringValue(item.grantId ?? item.grant_id),
        appCode: stringValue(item.appCode ?? item.app_code),
        cycleKey: stringValue(item.cycleKey ?? item.cycle_key),
        eventId: stringValue(item.eventId ?? item.event_id),
        transactionId: stringValue(item.transactionId ?? item.transaction_id),
        commandId: stringValue(item.commandId ?? item.command_id),
        userId: stringValue(item.userId ?? item.user_id),
        user: {
            userId: stringValue(rawUser.userId ?? rawUser.user_id),
            displayUserId: stringValue(rawUser.displayUserId ?? rawUser.display_user_id),
            prettyDisplayUserId: stringValue(rawUser.prettyDisplayUserId ?? rawUser.pretty_display_user_id),
            prettyId: stringValue(rawUser.prettyId ?? rawUser.pretty_id),
            username: stringValue(rawUser.username),
            avatar: stringValue(rawUser.avatar),
        },
        tierId: numberValue(item.tierId ?? item.tier_id),
        tierCode: stringValue(item.tierCode ?? item.tier_code),
        resourceGroupId: numberValue(item.resourceGroupId ?? item.resource_group_id),
        thresholdUsdMinor: numberValue(item.thresholdUsdMinor ?? item.threshold_usd_minor),
        reachedUsdMinor: numberValue(item.reachedUsdMinor ?? item.reached_usd_minor),
        qualifyingUsdMinor: numberValue(item.qualifyingUsdMinor ?? item.qualifying_usd_minor),
        rechargeCoinAmount: numberValue(item.rechargeCoinAmount ?? item.recharge_coin_amount),
        rechargeType: stringValue(item.rechargeType ?? item.recharge_type),
        status: stringValue(item.status),
        walletCommandId: stringValue(item.walletCommandId ?? item.wallet_command_id),
        walletGrantId: stringValue(item.walletGrantId ?? item.wallet_grant_id),
        failureReason: stringValue(item.failureReason ?? item.failure_reason),
        grantedAtMs: numberValue(item.grantedAtMs ?? item.granted_at_ms),
        createdAtMs: numberValue(item.createdAtMs ?? item.created_at_ms),
        updatedAtMs: numberValue(item.updatedAtMs ?? item.updated_at_ms),
    };
}

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;
}
