/**
 * Contact System Type Definitions
 *
 * Centralized type definitions for the contact form submission system.
 * These types ensure type safety across the dual-database architecture.
 *
 * @module lib/types/contact.types
 */

/**
 * Contact submission data from the public contact form
 * This represents user-submitted data before validation
 */
export interface ContactFormData {
  /** Full name of the person submitting */
  name: string;

  /** Email address for contact */
  email: string;

  /** Optional phone number (validated if provided) */
  phone?: string;

  /** Optional company/organization name */
  company?: string;

  /** Topic/category of the inquiry (sales, support, etc.) */
  topic: string;

  /** Message content (minimum 10 characters) */
  message: string;

  /** User's preferred language for responses */
  preferredLanguage: 'ar' | 'en';

  /** Whether user consented to privacy policy */
  consentGiven: boolean;

  /** reCAPTCHA token for bot protection */
  recaptchaToken: string;
}

/**
 * Sanitized contact data ready for database insertion
 * All fields have been validated and sanitized
 */
export interface SanitizedContactData {
  /** Sanitized name (XSS-safe) */
  name: string;

  /** Normalized and validated email */
  email: string;

  /** Sanitized phone number or empty string */
  phone: string;

  /** Sanitized company name or null */
  company: string | null;

  /** Validated topic from allowed list */
  topic: string;

  /** Sanitized message content */
  message: string;

  /** Validated language preference */
  preferredLanguage: 'ar' | 'en';

  /** Consent confirmation */
  consentGiven: boolean;
}

/**
 * Contact data for dual-database save operation
 * Used by saveContactToBoth() helper
 */
export interface ContactSaveData {
  /** Optional pre-generated ID (auto-generated if not provided) */
  id?: string;

  /** Full name */
  name: string;

  /** Email address */
  email: string;

  /** Optional phone number */
  phone?: string;

  /** Optional company name */
  company?: string;

  /** Inquiry topic/category */
  topic?: string;

  /** Message content */
  message: string;

  /** Preferred response language */
  preferredLanguage: 'ar' | 'en';

  /** Privacy consent given */
  consentGiven: boolean;

  /** IP address of submitter (for security) */
  ipAddress?: string;

  /** User agent string (for analytics) */
  userAgent?: string;
}

/**
 * Contact record as stored in Prisma database
 * Used by staff dashboard for contact management
 */
export interface PrismaContact {
  /** Unique identifier (CUID) */
  id: string;

  /** Contact's name */
  name: string;

  /** Contact's email */
  email: string;

  /** Optional phone number */
  phone: string | null;

  /** Optional company name */
  company: string | null;

  /** Message content */
  message: string;

  /** Language preference ('ar' or 'en') */
  language: string;

  /** Current status of the contact */
  status: ContactStatus;

  /** ID of staff member assigned to this contact */
  assignedTo: string | null;

  /** ID of staff member who responded */
  respondedBy: string | null;

  /** Timestamp when response was sent */
  respondedAt: Date | null;

  /** Internal notes (staff only) */
  internalNotes: string | null;

  /** Creation timestamp */
  createdAt: Date;

  /** Last update timestamp */
  updatedAt: Date;
}

/**
 * File attachment metadata
 */
export interface AttachmentMetadata {
  /** Original filename */
  name: string;

  /** File size in bytes */
  size: number;

  /** MIME type */
  type: string;

  /** Storage path */
  path: string;

  /** Signed URL for access (expires) */
  signedUrl: string | null;

  /** Storage bucket name */
  bucket: string;
}

/**
 * Contact status enum
 * Tracks the lifecycle of a contact submission
 */
export enum ContactStatus {
  /** Newly submitted, not yet viewed */
  NEW = 'NEW',

  /** Viewed by staff but no action taken */
  READ = 'READ',

  /** Staff is working on response */
  IN_PROGRESS = 'IN_PROGRESS',

  /** Response has been sent */
  RESPONDED = 'RESPONDED',

  /** Issue resolved and closed */
  CLOSED = 'CLOSED',

  /** Marked as spam */
  SPAM = 'SPAM',
}

/**
 * Valid contact topics/categories
 * Must match options in contact form
 */
export const VALID_CONTACT_TOPICS = [
  'sales',
  'support',
  'billing',
  'partnerships',
  'press',
  'careers',
  'security',
  'demo',
  'other',
] as const;

export type ContactTopic = typeof VALID_CONTACT_TOPICS[number];

/**
 * Validation error structure
 */
export interface ContactValidationError {
  /** Field name that failed validation */
  field: string;

  /** Human-readable error message */
  message: string;

  /** Optional error code for programmatic handling */
  code?: string;
}

/**
 * API response for successful submission
 */
export interface ContactSubmissionResponse {
  /** Whether submission was successful */
  success: true;

  /** Unique ID of the created submission */
  submissionId: string;

  /** Success message to display to user */
  message: string;
}

/**
 * API response for failed submission
 */
export interface ContactSubmissionError {
  /** Whether submission failed */
  success?: false;

  /** Error message */
  error: string;

  /** Optional validation errors */
  errors?: ContactValidationError[];

  /** Optional retry-after time for rate limiting */
  retryAfter?: number;
}

/**
 * Contact filters for staff dashboard
 */
export interface ContactFilters {
  /** Filter by status */
  status?: ContactStatus | 'all';

  /** Search by name, email, or company */
  search?: string;

  /** Filter by assigned staff member */
  assignedTo?: string;

  /** Filter by date range */
  dateFrom?: Date;
  dateTo?: Date;

  /** Filter by topic */
  topic?: ContactTopic;

  /** Filter by language */
  language?: 'ar' | 'en';
}

/**
 * Paginated contact list response
 */
export interface ContactListResponse {
  /** Array of contact records */
  contacts: PrismaContact[];

  /** Total count of contacts (before pagination) */
  total: number;

  /** Current page number */
  page: number;

  /** Number of items per page */
  perPage: number;

  /** Whether there are more pages */
  hasMore: boolean;
}

/**
 * Contact status update request
 */
export interface ContactStatusUpdate {
  /** ID of contact to update */
  contactId: string;

  /** New status */
  status: ContactStatus;

  /** Optional internal notes to add */
  notes?: string;

  /** Optional staff member to assign */
  assignTo?: string;
}

/**
 * Staff user context (minimal info for authorization)
 */
export interface StaffUser {
  /** Staff user ID */
  id: string;

  /** Staff role (for permission checks) */
  role: string;

  /** Staff name */
  name?: string;

  /** Staff email */
  email?: string;
}

/**
 * Rate limit configuration
 */
export interface RateLimitConfig {
  /** Maximum requests allowed */
  maxRequests: number;

  /** Time window (e.g., '5 m', '1 h') */
  window: string;

  /** Redis key prefix */
  prefix: string;
}

/**
 * Database save result
 */
export interface SaveResult<T> {
  /** Whether save was successful */
  success: boolean;

  /** The saved data (if successful) */
  data?: T;

  /** Error message (if failed) */
  error?: string;

  /** Which databases succeeded */
  savedTo?: {
    prisma: boolean;
    convex: boolean;
  };
}
