export type SettingScope = 'department' | 'company' | 'global';

export type SettingSource = 'department' | 'company' | 'global' | 'default';

export type SettingValueType = 'string' | 'number' | 'boolean' | 'json' | 'array';

export interface SettingItem {
  key: string;
  value: unknown;
  group: string;
  label: string;
  description?: string | null;
  type: SettingValueType;
  default_value: unknown;
  is_public: boolean;
  is_encrypted?: boolean;
  source: SettingSource;
  source_scope_id?: string | null;
}

export interface SettingDefinition {
  id: string;
  key: string;
  group: string;
  label: Record<string, string> | string;
  description?: Record<string, string> | string | null;
  type: SettingValueType;
  default_value: unknown;
  validation_rules?: string[] | Record<string, unknown>;
  is_public: boolean;
  is_encrypted: boolean;
  sort_order: number;
}

export interface SettingMetadata {
  value: unknown;
  source: SettingSource;
  scope_id: string | null;
}

export function isSettingItem(value: unknown): value is SettingItem {
  if (typeof value !== 'object' || value === null) {
    return false;
  }
  const s = value as Record<string, unknown>;
  return typeof s.key === 'string' && 'value' in s && typeof s.type === 'string';
}

export function isSettingDefinition(value: unknown): value is SettingDefinition {
  if (typeof value !== 'object' || value === null) {
    return false;
  }
  const d = value as Record<string, unknown>;
  return typeof d.key === 'string' && typeof d.type === 'string';
}

export function parseSettingsMap(raw: unknown): Record<string, SettingItem> {
  if (typeof raw !== 'object' || raw === null) {
    return {};
  }

  const envelope = raw as Record<string, unknown>;
  const data =
    envelope.success === true && typeof envelope.data === 'object' && envelope.data !== null
      ? (envelope.data as Record<string, unknown>)
      : envelope;

  const map: Record<string, SettingItem> = {};

  for (const [key, entry] of Object.entries(data)) {
    if (isSettingItem(entry)) {
      map[key] = entry;
    } else if (typeof entry === 'object' && entry !== null && isSettingItem({ key, ...entry })) {
      map[key] = { key, ...(entry as Omit<SettingItem, 'key'>) };
    }
  }

  return map;
}

export function localizedSettingText(
  field: Record<string, string> | string | null | undefined,
  locale: string,
): string {
  if (!field) {
    return '';
  }
  if (typeof field === 'string') {
    return field;
  }
  return field[locale] ?? field.en ?? Object.values(field)[0] ?? '';
}

export function formatSettingValue(value: unknown, isEncrypted: boolean, revealed: boolean): string {
  if (isEncrypted && !revealed) {
    return '••••••••';
  }
  if (value === null || value === undefined) {
    return '';
  }
  if (typeof value === 'boolean') {
    return value ? 'true' : 'false';
  }
  if (typeof value === 'object') {
    return JSON.stringify(value, null, 2);
  }
  return String(value);
}
