export const normalizeAdminSettings = (raw) => {
  if (!raw) {
    return null;
  }
  return {
    scheduleCron: raw.scheduleCron || '',
    pickupFallbackCron: raw.pickupFallbackCron || '',
    pickupWindowOffsetsMinutes: Array.isArray(raw.pickupWindowOffsetsMinutes)
      ? raw.pickupWindowOffsetsMinutes.join(', ')
      : '',
    regularPickupRefreshCron: raw.regularPickupRefreshCron || '',
    dormantMembershipCron: raw.dormantMembershipCron || '',
    randomDelayMinSeconds: raw.randomDelayMinSeconds ?? '',
    randomDelayMaxSeconds: raw.randomDelayMaxSeconds ?? '',
    initialDelayMinSeconds: raw.initialDelayMinSeconds ?? '',
    initialDelayMaxSeconds: raw.initialDelayMaxSeconds ?? '',
    storePickupCheckDelayMs: raw.storePickupCheckDelayMs ?? '',
    storeWatchCron: raw.storeWatchCron || '',
    storeWatchInitialDelayMinSeconds: raw.storeWatchInitialDelayMinSeconds ?? '',
    storeWatchInitialDelayMaxSeconds: raw.storeWatchInitialDelayMaxSeconds ?? '',
    storeWatchRequestDelayMs: raw.storeWatchRequestDelayMs ?? '',
    storeWatchStatusCacheMaxAgeMinutes: raw.storeWatchStatusCacheMaxAgeMinutes ?? '',
    messageWatcherSocketEnabled:
      raw.messageWatcherSocketEnabled === undefined ? true : !!raw.messageWatcherSocketEnabled,
    messageWatcherFallbackEnabled:
      raw.messageWatcherFallbackEnabled === undefined ? true : !!raw.messageWatcherFallbackEnabled,
    messageWatcherFallbackCron: raw.messageWatcherFallbackCron || '0 6-23 * * *',
    messageWatcherDebugLogging:
      raw.messageWatcherDebugLogging === undefined ? true : !!raw.messageWatcherDebugLogging,
    maintenanceModeActive: !!raw.maintenanceModeActive,
    maintenanceModeAutoEnabled:
      raw.maintenanceModeAutoEnabled === undefined ? true : !!raw.maintenanceModeAutoEnabled,
    maintenanceModeActivatedAt: raw.maintenanceModeActivatedAt || '',
    maintenanceModeReason: raw.maintenanceModeReason || '',
    maintenanceModeErrorThreshold: raw.maintenanceModeErrorThreshold ?? '',
    maintenanceModeErrorWindowMinutes: raw.maintenanceModeErrorWindowMinutes ?? '',
    ignoredSlots: Array.isArray(raw.ignoredSlots)
      ? raw.ignoredSlots.map((slot) => ({
          storeId: slot?.storeId ? String(slot.storeId) : '',
          slotName: slot?.slotName || slot?.description || '',
          info: slot?.info || ''
        }))
      : [],
    notifications: {
      ntfy: {
        enabled: !!raw.notifications?.ntfy?.enabled,
        serverUrl: raw.notifications?.ntfy?.serverUrl || 'https://ntfy.sh',
        topicPrefix: raw.notifications?.ntfy?.topicPrefix || '',
        username: raw.notifications?.ntfy?.username || '',
        password: raw.notifications?.ntfy?.password || ''
      },
      telegram: {
        enabled: !!raw.notifications?.telegram?.enabled,
        botToken: raw.notifications?.telegram?.botToken || '',
        chatId: raw.notifications?.telegram?.chatId || ''
      }
    }
  };
};

const toNumberOrUndefined = (value) => {
  if (value === '' || value === null || value === undefined) {
    return undefined;
  }
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : undefined;
};

const toNumberArray = (value) => {
  if (Array.isArray(value)) {
    return value
      .map((entry) => Number(entry))
      .filter((entry) => Number.isFinite(entry));
  }
  if (typeof value !== 'string') {
    return undefined;
  }
  const parsed = value
    .split(',')
    .map((entry) => Number(entry.trim()))
    .filter((entry) => Number.isFinite(entry));
  return parsed.length > 0 ? parsed : undefined;
};

export const serializeAdminSettings = (adminSettings) => {
  if (!adminSettings) {
    return null;
  }
  return {
    scheduleCron: adminSettings.scheduleCron,
    pickupFallbackCron: adminSettings.pickupFallbackCron,
    pickupWindowOffsetsMinutes: toNumberArray(adminSettings.pickupWindowOffsetsMinutes),
    regularPickupRefreshCron: adminSettings.regularPickupRefreshCron,
    dormantMembershipCron: adminSettings.dormantMembershipCron,
    randomDelayMinSeconds: toNumberOrUndefined(adminSettings.randomDelayMinSeconds),
    randomDelayMaxSeconds: toNumberOrUndefined(adminSettings.randomDelayMaxSeconds),
    initialDelayMinSeconds: toNumberOrUndefined(adminSettings.initialDelayMinSeconds),
    initialDelayMaxSeconds: toNumberOrUndefined(adminSettings.initialDelayMaxSeconds),
    storePickupCheckDelayMs: toNumberOrUndefined(adminSettings.storePickupCheckDelayMs),
    storeWatchCron: adminSettings.storeWatchCron,
    storeWatchInitialDelayMinSeconds: toNumberOrUndefined(adminSettings.storeWatchInitialDelayMinSeconds),
    storeWatchInitialDelayMaxSeconds: toNumberOrUndefined(adminSettings.storeWatchInitialDelayMaxSeconds),
    storeWatchRequestDelayMs: toNumberOrUndefined(adminSettings.storeWatchRequestDelayMs),
    storeWatchStatusCacheMaxAgeMinutes: toNumberOrUndefined(adminSettings.storeWatchStatusCacheMaxAgeMinutes),
    messageWatcherSocketEnabled: !!adminSettings.messageWatcherSocketEnabled,
    messageWatcherFallbackEnabled: !!adminSettings.messageWatcherFallbackEnabled,
    messageWatcherFallbackCron: adminSettings.messageWatcherFallbackCron || '',
    messageWatcherDebugLogging: !!adminSettings.messageWatcherDebugLogging,
    maintenanceModeActive: !!adminSettings.maintenanceModeActive,
    maintenanceModeAutoEnabled: !!adminSettings.maintenanceModeAutoEnabled,
    maintenanceModeActivatedAt: adminSettings.maintenanceModeActivatedAt || null,
    maintenanceModeReason: adminSettings.maintenanceModeReason || '',
    maintenanceModeErrorThreshold: toNumberOrUndefined(adminSettings.maintenanceModeErrorThreshold),
    maintenanceModeErrorWindowMinutes: toNumberOrUndefined(adminSettings.maintenanceModeErrorWindowMinutes),
    ignoredSlots: (adminSettings.ignoredSlots || []).map((slot) => ({
      storeId: slot.storeId || '',
      slotName: slot.slotName || '',
      info: slot.info || ''
    })),
    notifications: {
      ntfy: {
        enabled: !!adminSettings.notifications?.ntfy?.enabled,
        serverUrl: adminSettings.notifications?.ntfy?.serverUrl || '',
        topicPrefix: adminSettings.notifications?.ntfy?.topicPrefix || '',
        username: adminSettings.notifications?.ntfy?.username || '',
        password: adminSettings.notifications?.ntfy?.password || ''
      },
      telegram: {
        enabled: !!adminSettings.notifications?.telegram?.enabled,
        botToken: adminSettings.notifications?.telegram?.botToken || '',
        chatId: adminSettings.notifications?.telegram?.chatId || ''
      }
    }
  };
};
