/**
 * User Preferences Configuration
 *
 * Centralized configuration for user preferences system including:
 * - Notification type definitions with i18n labels
 * - Timezone options for GCC countries
 * - Default preference values
 * - Validation schemas
 *
 * @module lib/config/preferences.config
 */

import type {
  EmailNotificationPreferences,
  NotificationLanguage,
} from "@/lib/types/notification.types";

/**
 * Notification type definition with labels for both languages
 */
export interface NotificationTypeConfig {
  /** Unique identifier matching EmailNotificationPreferences key */
  key: keyof EmailNotificationPreferences;
  /** English label */
  labelEn: string;
  /** Arabic label */
  labelAr: string;
  /** English description */
  descriptionEn?: string;
  /** Arabic description */
  descriptionAr?: string;
  /** Whether this notification type is mandatory (cannot be disabled) */
  mandatory?: boolean;
  /** Icon name (for UI rendering) */
  icon?: string;
}

/**
 * All notification types with localized labels
 *
 * @example
 * ```typescript
 * NOTIFICATION_TYPES.map(type => (
 *   <div key={type.key}>
 *     {isArabic ? type.labelAr : type.labelEn}
 *   </div>
 * ))
 * ```
 */
export const NOTIFICATION_TYPES: readonly NotificationTypeConfig[] = [
  {
    key: "bookings",
    labelEn: "New bookings",
    labelAr: "حجوزات جديدة",
    descriptionEn: "Get notified when new appointments are booked",
    descriptionAr: "احصل على إشعار عند حجز مواعيد جديدة",
    icon: "calendar",
  },
  {
    key: "reminders",
    labelEn: "Appointment reminders",
    labelAr: "تذكيرات المواعيد",
    descriptionEn: "Receive reminders before your appointments",
    descriptionAr: "احصل على تذكيرات قبل مواعيدك",
    icon: "bell",
  },
  {
    key: "payments",
    labelEn: "Payment receipts",
    labelAr: "إيصالات الدفع",
    descriptionEn: "Receive receipts for all payments",
    descriptionAr: "احصل على إيصالات لجميع المدفوعات",
    mandatory: true, // Cannot be disabled for compliance
    icon: "receipt",
  },
  {
    key: "marketing",
    labelEn: "Marketing emails",
    labelAr: "رسائل تسويقية",
    descriptionEn: "Updates about new features and promotions",
    descriptionAr: "تحديثات حول الميزات والعروض الجديدة",
    icon: "megaphone",
  },
  {
    key: "security",
    labelEn: "Security alerts",
    labelAr: "تنبيهات أمنية",
    descriptionEn: "Important notifications about your account security",
    descriptionAr: "إشعارات مهمة حول أمان حسابك",
    mandatory: true, // Cannot be disabled for security
    icon: "shield",
  },
  {
    key: "weeklyReport",
    labelEn: "Weekly report",
    labelAr: "تقرير أسبوعي",
    descriptionEn: "Summary of your weekly activity",
    descriptionAr: "ملخص نشاطك الأسبوعي",
    icon: "chart",
  },
] as const;

/**
 * Timezone configuration with labels
 */
export interface TimezoneConfig {
  /** IANA timezone identifier */
  value: string;
  /** English label */
  labelEn: string;
  /** Arabic label */
  labelAr: string;
  /** GMT offset display */
  offset: string;
  /** Country code (ISO 3166-1 alpha-2) */
  countryCode: string;
  /** Whether this is the default timezone */
  default?: boolean;
}

/**
 * Available timezones (GCC countries)
 *
 * @example
 * ```typescript
 * <select>
 *   {TIMEZONE_OPTIONS.map(tz => (
 *     <option key={tz.value} value={tz.value}>
 *       {isArabic ? tz.labelAr : tz.labelEn} ({tz.offset})
 *     </option>
 *   ))}
 * </select>
 * ```
 */
export const TIMEZONE_OPTIONS: readonly TimezoneConfig[] = [
  {
    value: "Asia/Qatar",
    labelEn: "Qatar",
    labelAr: "قطر",
    offset: "GMT+3",
    countryCode: "QA",
    default: true,
  },
  {
    value: "Asia/Dubai",
    labelEn: "UAE",
    labelAr: "الإمارات",
    offset: "GMT+4",
    countryCode: "AE",
  },
  {
    value: "Asia/Riyadh",
    labelEn: "Saudi Arabia",
    labelAr: "السعودية",
    offset: "GMT+3",
    countryCode: "SA",
  },
  {
    value: "Asia/Kuwait",
    labelEn: "Kuwait",
    labelAr: "الكويت",
    offset: "GMT+3",
    countryCode: "KW",
  },
  {
    value: "Asia/Bahrain",
    labelEn: "Bahrain",
    labelAr: "البحرين",
    offset: "GMT+3",
    countryCode: "BH",
  },
  {
    value: "Asia/Muscat",
    labelEn: "Oman",
    labelAr: "عمان",
    offset: "GMT+4",
    countryCode: "OM",
  },
] as const;

/**
 * Date format options
 */
export interface DateFormatConfig {
  /** Format identifier */
  value: string;
  /** English label */
  labelEn: string;
  /** Arabic label */
  labelAr: string;
  /** Example display */
  example: string;
}

/**
 * Available date formats
 */
export const DATE_FORMAT_OPTIONS: readonly DateFormatConfig[] = [
  {
    value: "DD/MM/YYYY",
    labelEn: "Day/Month/Year",
    labelAr: "يوم/شهر/سنة",
    example: "25/12/2025",
  },
  {
    value: "MM/DD/YYYY",
    labelEn: "Month/Day/Year",
    labelAr: "شهر/يوم/سنة",
    example: "12/25/2025",
  },
  {
    value: "YYYY-MM-DD",
    labelEn: "Year-Month-Day",
    labelAr: "سنة-شهر-يوم",
    example: "2025-12-25",
  },
] as const;

/**
 * Email frequency options
 */
export interface EmailFrequencyConfig {
  /** Frequency identifier */
  value: "instant" | "daily" | "weekly";
  /** English label */
  labelEn: string;
  /** Arabic label */
  labelAr: string;
  /** English description */
  descriptionEn: string;
  /** Arabic description */
  descriptionAr: string;
}

/**
 * Email frequency options
 */
export const EMAIL_FREQUENCY_OPTIONS: readonly EmailFrequencyConfig[] = [
  {
    value: "instant",
    labelEn: "Instant",
    labelAr: "فوري",
    descriptionEn: "Receive emails immediately",
    descriptionAr: "استلم الرسائل فوراً",
  },
  {
    value: "daily",
    labelEn: "Daily digest",
    labelAr: "ملخص يومي",
    descriptionEn: "Once per day summary",
    descriptionAr: "ملخص مرة واحدة يومياً",
  },
  {
    value: "weekly",
    labelEn: "Weekly digest",
    labelAr: "ملخص أسبوعي",
    descriptionEn: "Once per week summary",
    descriptionAr: "ملخص مرة واحدة أسبوعياً",
  },
] as const;

/**
 * Dashboard view density options
 */
export type ViewDensity = "comfortable" | "compact";

export interface ViewDensityConfig {
  value: ViewDensity;
  labelEn: string;
  labelAr: string;
}

export const VIEW_DENSITY_OPTIONS: readonly ViewDensityConfig[] = [
  {
    value: "comfortable",
    labelEn: "Comfortable",
    labelAr: "مريح",
  },
  {
    value: "compact",
    labelEn: "Compact",
    labelAr: "مضغوط",
  },
] as const;

/**
 * Default email notification preferences
 */
export const DEFAULT_EMAIL_NOTIFICATIONS: EmailNotificationPreferences = {
  bookings: true,
  reminders: true,
  payments: true,
  marketing: false,
  security: true,
  weeklyReport: false,
} as const;

/**
 * Default dashboard preferences
 */
export const DEFAULT_DASHBOARD_PREFERENCES = {
  defaultTab: "overview",
  refreshInterval: 60, // seconds
  viewDensity: "comfortable" as ViewDensity,
} as const;

/**
 * Complete default preferences object
 *
 * Used when creating new user preferences
 *
 * @example
 * ```typescript
 * const newPreferences = await prisma.user_preferences.create({
 *   data: {
 *     id: createId(),
 *     userId: user.id,
 *     ...DEFAULT_PREFERENCES,
 *   },
 * });
 * ```
 */
export const DEFAULT_PREFERENCES = {
  language: "ar" as NotificationLanguage,
  timezone: "Asia/Qatar",
  dateFormat: "DD/MM/YYYY",
  emailNotifications: DEFAULT_EMAIL_NOTIFICATIONS,
  emailFrequency: "instant" as const,
  dashboardPreferences: DEFAULT_DASHBOARD_PREFERENCES,
} as const;

/**
 * Validation rules for preferences
 */
export const PREFERENCES_VALIDATION = {
  /** Valid language codes */
  VALID_LANGUAGES: ["ar", "en"] as const,

  /** Valid email frequency values */
  VALID_EMAIL_FREQUENCIES: ["instant", "daily", "weekly"] as const,

  /** Valid date formats */
  VALID_DATE_FORMATS: ["DD/MM/YYYY", "MM/DD/YYYY", "YYYY-MM-DD"] as const,

  /** Valid timezones (extracted from TIMEZONE_OPTIONS) */
  VALID_TIMEZONES: TIMEZONE_OPTIONS.map((tz) => tz.value),

  /** Valid view density options */
  VALID_VIEW_DENSITIES: ["comfortable", "compact"] as const,

  /** Dashboard refresh interval constraints (in seconds) */
  REFRESH_INTERVAL: {
    MIN: 30,
    MAX: 300,
    DEFAULT: 60,
  },
} as const;

/**
 * Helper function to get notification type config by key
 *
 * @param key - Notification type key
 * @returns Notification type configuration or undefined
 */
export function getNotificationTypeConfig(
  key: keyof EmailNotificationPreferences,
): NotificationTypeConfig | undefined {
  return NOTIFICATION_TYPES.find((type) => type.key === key);
}

/**
 * Helper function to get timezone config by value
 *
 * @param value - IANA timezone identifier
 * @returns Timezone configuration or undefined
 */
export function getTimezoneConfig(value: string): TimezoneConfig | undefined {
  return TIMEZONE_OPTIONS.find((tz) => tz.value === value);
}

/**
 * Helper function to check if a timezone is valid
 *
 * @param timezone - Timezone to validate
 * @returns true if valid, false otherwise
 */
export function isValidTimezone(timezone: string): boolean {
  return PREFERENCES_VALIDATION.VALID_TIMEZONES.includes(timezone);
}

/**
 * Helper function to check if a language is valid
 *
 * @param language - Language to validate
 * @returns true if valid, false otherwise
 */
export function isValidLanguage(
  language: string,
): language is NotificationLanguage {
  return PREFERENCES_VALIDATION.VALID_LANGUAGES.includes(language as any);
}

/**
 * Helper function to check if an email frequency is valid
 *
 * @param frequency - Email frequency to validate
 * @returns true if valid, false otherwise
 */
export function isValidEmailFrequency(
  frequency: string,
): frequency is "instant" | "daily" | "weekly" {
  return PREFERENCES_VALIDATION.VALID_EMAIL_FREQUENCIES.includes(
    frequency as any,
  );
}

/**
 * Helper function to validate dashboard refresh interval
 *
 * @param interval - Refresh interval in seconds
 * @returns Validated interval (clamped to min/max)
 */
export function validateRefreshInterval(interval: number): number {
  const { MIN, MAX, DEFAULT } = PREFERENCES_VALIDATION.REFRESH_INTERVAL;

  if (typeof interval !== "number" || isNaN(interval)) {
    return DEFAULT;
  }

  return Math.max(MIN, Math.min(MAX, interval));
}

/**
 * Type guard to check if notification type is mandatory
 *
 * @param key - Notification type key
 * @returns true if mandatory, false otherwise
 */
export function isMandatoryNotification(
  key: keyof EmailNotificationPreferences,
): boolean {
  const config = getNotificationTypeConfig(key);
  return config?.mandatory === true;
}
