import { requestClient } from '#/api/request';

export namespace NotificationApi {
  export type ConfigSectionKey = 'activeNotis' | 'inactiveNotis' | 'presentations' | 'schedules';

  export interface TickValue {
    ticks: number | string;
  }

  export interface ScheduleItem {
    cancelType: number;
    cancelValue: number;
    deltaTime: TickValue;
    fireTime: TickValue;
    id: number;
    repeatInterval: number;
    repeats: boolean;
    scheduleType: number;
  }

  export interface LocalizedText {
    language: number;
    locText: string;
    param: number;
  }

  export interface PresentationItem {
    id: number;
    infos: LocalizedText[];
    titles: LocalizedText[];
  }

  export interface NoticeItem {
    conditionId: number;
    id: number;
    presentationId: number;
    scheduleId: number;
  }

  export interface NotificationConfig {
    activeNotis: NoticeItem[];
    inactiveNotis: NoticeItem[];
    presentations: PresentationItem[];
    schedules: ScheduleItem[];
  }

  export interface ConfigState {
    config: NotificationConfig;
    updated_at: string;
  }
}

const NOTIFICATION_CONFIG_BASE_URL = '/config/notification';
function normalizeForCSharp(value: any): any {
  if (Array.isArray(value)) {
    return value.map((item) => normalizeForCSharp(item));
  }
  if (value && typeof value === 'object') {
    return Object.fromEntries(
      Object.entries(value).map(([key, currentValue]) => {
        if (key === 'ticks' && currentValue != null) {
          return [key, String(currentValue)];
        }
        return [key, normalizeForCSharp(currentValue)];
      }),
    );
  }
  return value;
}

function normalizeConfigState(parsed: NotificationApi.ConfigState) {
  return {
    config: normalizeForCSharp(parsed.config),
    updated_at: parsed.updated_at,
  } satisfies NotificationApi.ConfigState;
}

export async function getNotificationConfigApi() {
  const state = await requestClient.get<NotificationApi.ConfigState>(
    NOTIFICATION_CONFIG_BASE_URL,
  );
  return normalizeConfigState(state);
}


export async function updateNotificationConfigApi(params: NotificationApi.NotificationConfig) {
  const state = await requestClient.put<NotificationApi.ConfigState>(
    `${NOTIFICATION_CONFIG_BASE_URL}/update`,
    { config: JSON.stringify(normalizeForCSharp(params)) },
  );
  return normalizeConfigState(state);
}