/**
 * Notification Types
 *
 * TypeScript interfaces for email notification preferences and services
 *
 * @module lib/types/notification.types
 */

/**
 * User email notification preferences
 * Matches the JSON structure in user_preferences.emailNotifications
 */
export interface EmailNotificationPreferences {
  /** New booking confirmations */
  bookings: boolean;
  /** Appointment reminders */
  reminders: boolean;
  /** Payment receipts */
  payments: boolean;
  /** Marketing emails */
  marketing: boolean;
  /** Security alerts (login, password changes) */
  security: boolean;
  /** Weekly summary reports */
  weeklyReport: boolean;
}

/**
 * Notification type identifier
 */
export type NotificationType = keyof EmailNotificationPreferences;

/**
 * Supported languages for notifications
 */
export type NotificationLanguage = 'ar' | 'en';

/**
 * Base data for all notification emails
 */
export interface BaseNotificationData {
  /** User ID */
  userId: string;
  /** User email address */
  email: string;
  /** User's preferred language */
  language: NotificationLanguage;
  /** User's name for personalization */
  name?: string;
  /** User's timezone */
  timezone?: string;
}

/**
 * Preferences change confirmation email data
 */
export interface PreferencesConfirmationData extends BaseNotificationData {
  /** Previous preferences state */
  previousPreferences: Partial<EmailNotificationPreferences>;
  /** New preferences state */
  newPreferences: EmailNotificationPreferences;
  /** List of changed settings */
  changes: PreferenceChange[];
}

/**
 * Single preference change record
 */
export interface PreferenceChange {
  /** Setting name */
  setting: NotificationType | 'language' | 'timezone';
  /** Previous value */
  previousValue: boolean | string;
  /** New value */
  newValue: boolean | string;
}

/**
 * New booking notification email data
 */
export interface BookingNotificationData extends BaseNotificationData {
  /** Booking ID */
  bookingId: string;
  /** Customer name */
  customerName: string;
  /** Customer phone */
  customerPhone: string;
  /** Customer email (optional) */
  customerEmail?: string;
  /** Service name */
  service: string;
  /** Appointment date */
  appointmentDate: Date;
  /** Appointment time */
  appointmentTime: string;
  /** Duration in minutes */
  duration: number;
  /** Total amount */
  totalAmount: number;
  /** Deposit amount (if applicable) */
  depositAmount?: number;
  /** Source of booking */
  source: 'whatsapp' | 'manual' | 'widget' | 'phone_call' | 'walk_in';
}

/**
 * Appointment reminder email data
 */
export interface ReminderNotificationData extends BaseNotificationData {
  /** Booking ID */
  bookingId: string;
  /** Customer name */
  customerName: string;
  /** Service name */
  service: string;
  /** Appointment date */
  appointmentDate: Date;
  /** Appointment time */
  appointmentTime: string;
  /** Duration in minutes */
  duration: number;
  /** Hours until appointment */
  hoursUntil: number;
  /** Meeting link (if applicable) */
  meetingLink?: string;
  /** Staff member (if assigned) */
  staffMember?: string;
}

/**
 * Payment receipt email data
 */
export interface PaymentReceiptData extends BaseNotificationData {
  /** Payment ID */
  paymentId: string;
  /** Stripe payment intent ID */
  stripePaymentIntentId: string;
  /** Amount paid (in cents) */
  amount: number;
  /** Currency code (e.g., 'QAR', 'USD') */
  currency: string;
  /** Payment description */
  description?: string;
  /** Invoice ID (if applicable) */
  invoiceId?: string;
  /** Subscription ID (if applicable) */
  subscriptionId?: string;
  /** Payment date */
  paymentDate: Date;
  /** Card last 4 digits (if available) */
  cardLastFour?: string;
  /** Card brand (if available) */
  cardBrand?: string;
}

/**
 * Security alert types
 */
export type SecurityAlertType =
  | 'new_login'
  | 'password_changed'
  | 'email_changed'
  | 'suspicious_activity'
  | 'failed_login_attempts'
  | 'account_locked'
  | 'new_device'
  | 'new_location';

/**
 * Security alert email data
 */
export interface SecurityAlertData extends BaseNotificationData {
  /** Type of security alert */
  alertType: SecurityAlertType;
  /** IP address of the event */
  ipAddress: string;
  /** User agent string */
  userAgent?: string;
  /** Device name/type */
  deviceName?: string;
  /** Location (city, country) */
  location?: string;
  /** Country code */
  countryCode?: string;
  /** City */
  city?: string;
  /** Timestamp of the event */
  eventTime: Date;
  /** Additional details */
  details?: string;
  /** Number of failed attempts (for failed login alerts) */
  failedAttempts?: number;
  /** Account locked until (for account locked alerts) */
  lockedUntil?: Date;
}

/**
 * Weekly report email data
 */
export interface WeeklyReportData extends BaseNotificationData {
  /** Report period start date */
  periodStart: Date;
  /** Report period end date */
  periodEnd: Date;
  /** Appointments metrics */
  appointments: {
    /** Total new bookings this week */
    newBookings: number;
    /** Completed appointments */
    completed: number;
    /** Cancelled appointments */
    cancelled: number;
    /** Upcoming appointments (next week) */
    upcoming: number;
    /** Change from previous week (percentage) */
    changePercent: number;
  };
  /** Messages metrics */
  messages: {
    /** Total WhatsApp conversations */
    totalConversations: number;
    /** New conversations this week */
    newConversations: number;
    /** Messages received */
    received: number;
    /** Messages sent */
    sent: number;
    /** Change from previous week (percentage) */
    changePercent: number;
  };
  /** Payments metrics */
  payments: {
    /** Total revenue this week (in cents) */
    totalRevenue: number;
    /** Currency code */
    currency: string;
    /** Number of payments */
    paymentCount: number;
    /** Change from previous week (percentage) */
    changePercent: number;
  };
  /** Leads metrics */
  leads: {
    /** New leads this week */
    newLeads: number;
    /** Leads converted */
    converted: number;
    /** Total leads in pipeline */
    totalInPipeline: number;
    /** Change from previous week (percentage) */
    changePercent: number;
  };
}

/**
 * Marketing email data
 */
export interface MarketingEmailData extends BaseNotificationData {
  /** Campaign ID */
  campaignId?: string;
  /** Email subject */
  subject: string;
  /** Email content (HTML) */
  content: string;
  /** Call to action URL */
  ctaUrl?: string;
  /** Call to action text */
  ctaText?: string;
}

/**
 * Union type for all notification data types
 */
export type NotificationData =
  | PreferencesConfirmationData
  | BookingNotificationData
  | ReminderNotificationData
  | PaymentReceiptData
  | SecurityAlertData
  | WeeklyReportData
  | MarketingEmailData;

/**
 * Result of sending a notification email
 */
export interface NotificationResult {
  /** Whether the notification was sent successfully */
  success: boolean;
  /** Error message if failed */
  error?: string;
  /** Message ID from email provider */
  messageId?: string;
  /** Whether the notification was skipped due to preferences */
  skipped?: boolean;
  /** Reason for skipping */
  skipReason?: string;
}

/**
 * Email template structure
 */
export interface NotificationEmailTemplate {
  /** Email subject */
  subject: string;
  /** HTML body */
  html: string;
  /** Plain text body */
  text: string;
}

/**
 * Full user preferences (from database)
 */
export interface UserPreferences {
  id: string;
  userId: string;
  language: NotificationLanguage;
  timezone: string;
  dateFormat: string;
  emailNotifications: EmailNotificationPreferences;
  emailFrequency: 'instant' | 'daily' | 'weekly';
  dashboardPreferences: {
    defaultTab: string;
    viewDensity: 'comfortable' | 'compact';
    refreshInterval: number;
  };
  createdAt: Date;
  updatedAt: Date;
}
