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

export interface RiskConfigDto {
    appCode: string;
    maxAccountsPerDevice: number;
    updatedAtMs: number;
    updatedByAdminId: number;
}

export interface RiskConfigPayload {
    max_accounts_per_device: number;
}

type RawRiskConfig = RiskConfigDto & Record<string, unknown>;

export function getRiskConfig(): Promise<RiskConfigDto> {
    const endpoint = API_ENDPOINTS.getRiskConfig;
    return apiRequest<RawRiskConfig>(apiEndpointPath(API_OPERATIONS.getRiskConfig), {
        method: endpoint.method,
    }).then(normalizeRiskConfig);
}

export function updateRiskConfig(payload: RiskConfigPayload): Promise<RiskConfigDto> {
    const endpoint = API_ENDPOINTS.updateRiskConfig;
    return apiRequest<RawRiskConfig, RiskConfigPayload>(apiEndpointPath(API_OPERATIONS.updateRiskConfig), {
        body: payload,
        method: endpoint.method,
    }).then(normalizeRiskConfig);
}

function normalizeRiskConfig(data: RawRiskConfig): RiskConfigDto {
    return {
        appCode: stringValue(data.appCode ?? data.app_code),
        maxAccountsPerDevice: numberValue(data.maxAccountsPerDevice ?? data.max_accounts_per_device),
        updatedAtMs: numberValue(data.updatedAtMs ?? data.updated_at_ms),
        updatedByAdminId: numberValue(data.updatedByAdminId ?? data.updated_by_admin_id),
    };
}

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

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