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

export interface RegionBlockDto {
    blockId: number;
    keyword: string;
    countryCode: string;
    enabled: boolean;
    createdAtMs: number;
    updatedAtMs: number;
}

export interface IPWhitelistDto {
    whitelistId: number;
    ipAddress: string;
    enabled: boolean;
    createdAtMs: number;
    updatedAtMs: number;
}

export interface RegionBlockPayload {
    keywords: string[];
    whitelist_ips?: string[];
}

export interface RegionBlockConfigDto extends ApiList<RegionBlockDto> {
    whitelistItems: IPWhitelistDto[];
    whitelistTotal: number;
}

type RawRegionBlock = RegionBlockDto & Record<string, unknown>;
type RawIPWhitelist = IPWhitelistDto & Record<string, unknown>;
type RawRegionBlockConfig = ApiList<RawRegionBlock> & Record<string, unknown>;

export function listRegionBlocks(): Promise<RegionBlockConfigDto> {
    const endpoint = API_ENDPOINTS.listRegionBlocks;
    return apiRequest<RawRegionBlockConfig>(apiEndpointPath(API_OPERATIONS.listRegionBlocks), {
        method: endpoint.method,
    }).then(normalizeRegionBlockConfig);
}

export function replaceRegionBlocks(payload: RegionBlockPayload): Promise<RegionBlockConfigDto> {
    const endpoint = API_ENDPOINTS.replaceRegionBlocks;
    return apiRequest<RawRegionBlockConfig, RegionBlockPayload>(
        apiEndpointPath(API_OPERATIONS.replaceRegionBlocks),
        {
            body: payload,
            method: endpoint.method,
        },
    ).then(normalizeRegionBlockConfig);
}

function normalizeRegionBlockConfig(data: RawRegionBlockConfig): RegionBlockConfigDto {
    const rawWhitelist = (data.whitelistItems ?? data.whitelist_items ?? []) as RawIPWhitelist[];
    return {
        items: (data.items || []).map(normalizeRegionBlock),
        total: Number(data.total || 0),
        whitelistItems: rawWhitelist.map(normalizeIPWhitelist),
        whitelistTotal: numberValue(data.whitelistTotal ?? data.whitelist_total),
    };
}

function normalizeRegionBlock(item: RawRegionBlock): RegionBlockDto {
    return {
        blockId: numberValue(item.blockId ?? item.block_id),
        keyword: stringValue(item.keyword),
        countryCode: stringValue(item.countryCode ?? item.country_code),
        enabled: Boolean(item.enabled),
        createdAtMs: numberValue(item.createdAtMs ?? item.created_at_ms),
        updatedAtMs: numberValue(item.updatedAtMs ?? item.updated_at_ms),
    };
}

function normalizeIPWhitelist(item: RawIPWhitelist): IPWhitelistDto {
    return {
        whitelistId: numberValue(item.whitelistId ?? item.whitelist_id),
        ipAddress: stringValue(item.ipAddress ?? item.ip_address),
        enabled: Boolean(item.enabled),
        createdAtMs: numberValue(item.createdAtMs ?? item.created_at_ms),
        updatedAtMs: numberValue(item.updatedAtMs ?? item.updated_at_ms),
    };
}

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

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