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 RegistrationRewardConfigDto {
    appCode?: string;
    enabled: boolean;
    rewardType: string;
    coinAmount: number;
    resourceGroupId: number;
    dailyLimit: number;
    updatedByAdminId?: number;
    createdAtMs?: number;
    updatedAtMs?: number;
}

export interface RegistrationRewardConfigPayload {
    enabled: boolean;
    reward_type: string;
    coin_amount: number;
    resource_group_id: number;
    daily_limit: number;
}

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

export interface RegistrationRewardClaimDto {
    claimId: string;
    commandId?: string;
    userId: string;
    user?: RegistrationRewardClaimUserDto;
    rewardDay?: string;
    rewardType?: string;
    coinAmount?: number;
    resourceGroupId?: number;
    status?: string;
    walletCommandId?: string;
    walletTransactionId?: string;
    resourceGrantId?: string;
    failureReason?: string;
    claimedAtMs?: number;
    createdAtMs?: number;
    updatedAtMs?: number;
}

export interface RegistrationRewardClaimPageDto extends ApiPage<RegistrationRewardClaimDto> {
    todayClaimedCount: number;
}

type RawConfig = RegistrationRewardConfigDto & Record<string, unknown>;
type RawClaim = RegistrationRewardClaimDto & Record<string, unknown>;
type RawClaimPage = ApiPage<RawClaim> & Record<string, unknown>;

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

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

export function listRegistrationRewardClaims(query: PageQuery = {}): Promise<RegistrationRewardClaimPageDto> {
    const endpoint = API_ENDPOINTS.listRegistrationRewardClaims;
    return apiRequest<RawClaimPage>(apiEndpointPath(API_OPERATIONS.listRegistrationRewardClaims), {
        method: endpoint.method,
        query,
    }).then((page) => ({
        ...page,
        items: (page.items || []).map(normalizeClaim),
        todayClaimedCount: numberValue(page.todayClaimedCount ?? page.today_claimed_count),
    }));
}

function normalizeConfig(item: RawConfig): RegistrationRewardConfigDto {
    return {
        appCode: stringValue(item.appCode ?? item.app_code),
        enabled: Boolean(item.enabled),
        rewardType: stringValue(item.rewardType ?? item.reward_type) || "coin",
        coinAmount: numberValue(item.coinAmount ?? item.coin_amount),
        resourceGroupId: numberValue(item.resourceGroupId ?? item.resource_group_id),
        dailyLimit: numberValue(item.dailyLimit ?? item.daily_limit),
        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 normalizeClaim(item: RawClaim): RegistrationRewardClaimDto {
    const rawUser = (item.user || {}) as Record<string, unknown>;
    return {
        claimId: stringValue(item.claimId ?? item.claim_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),
        },
        rewardDay: stringValue(item.rewardDay ?? item.reward_day),
        rewardType: stringValue(item.rewardType ?? item.reward_type),
        coinAmount: numberValue(item.coinAmount ?? item.coin_amount),
        resourceGroupId: numberValue(item.resourceGroupId ?? item.resource_group_id),
        status: stringValue(item.status),
        walletCommandId: stringValue(item.walletCommandId ?? item.wallet_command_id),
        walletTransactionId: stringValue(item.walletTransactionId ?? item.wallet_transaction_id),
        resourceGrantId: stringValue(item.resourceGrantId ?? item.resource_grant_id),
        failureReason: stringValue(item.failureReason ?? item.failure_reason),
        claimedAtMs: numberValue(item.claimedAtMs ?? item.claimed_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;
}
