/**
 * POS API Types
 * Based on services/pos/app/models/ backend implementation
 */

// ============================================================================
// CORE POS TYPES
// ============================================================================

export type POSSystem = 'square' | 'toast' | 'lightspeed';

export type POSEnvironment = 'sandbox' | 'production';

export type POSTransactionType = 'sale' | 'refund' | 'void' | 'exchange';

export type POSTransactionStatus = 'completed' | 'pending' | 'failed' | 'refunded' | 'voided';

export type POSPaymentMethod = 'card' | 'cash' | 'digital_wallet' | 'other';

export type POSPaymentStatus = 'paid' | 'pending' | 'failed';

export type POSOrderType = 'dine_in' | 'takeout' | 'delivery' | 'pickup';

export type POSSyncStatus = 'success' | 'failed' | 'partial';

export type POSHealthStatus = 'healthy' | 'unhealthy' | 'unknown';

export type POSSyncType = 'full' | 'incremental' | 'manual' | 'webhook_triggered';

export type POSSyncDirection = 'inbound' | 'outbound' | 'bidirectional';

export type POSDataType = 'transactions' | 'products' | 'customers' | 'orders';

export type POSWebhookStatus = 'received' | 'processing' | 'processed' | 'failed';

// ============================================================================
// POS CONFIGURATION
// ============================================================================

export interface POSConfiguration {
  // Primary identifiers
  id: string;
  tenant_id: string;
  
  // POS Provider Information
  pos_system: POSSystem;
  provider_name: string;
  
  // Configuration Status
  is_active: boolean;
  is_connected: boolean;
  
  // Authentication & Credentials (encrypted)
  encrypted_credentials?: string;
  webhook_url?: string;
  webhook_secret?: string;
  
  // Provider-specific Settings
  environment: POSEnvironment;
  location_id?: string;
  merchant_id?: string;
  
  // Sync Configuration
  sync_enabled: boolean;
  sync_interval_minutes: string;
  auto_sync_products: boolean;
  auto_sync_transactions: boolean;
  
  // Last Sync Information
  last_sync_at?: string;
  last_successful_sync_at?: string;
  last_sync_status?: POSSyncStatus;
  last_sync_message?: string;
  
  // Provider-specific Configuration (JSON)
  provider_settings?: Record<string, any>;
  
  // Connection Health
  last_health_check_at?: string;
  health_status: POSHealthStatus;
  health_message?: string;
  
  // Timestamps
  created_at: string;
  updated_at: string;
  
  // Metadata
  created_by?: string;
  notes?: string;
}

// ============================================================================
// POS TRANSACTIONS
// ============================================================================

export interface POSTransaction {
  // Primary identifiers
  id: string;
  tenant_id: string;
  pos_config_id: string;
  
  // POS Provider Information
  pos_system: POSSystem;
  external_transaction_id: string;
  external_order_id?: string;
  
  // Transaction Details
  transaction_type: POSTransactionType;
  status: POSTransactionStatus;
  
  // Financial Information
  subtotal: number;
  tax_amount: number;
  tip_amount: number;
  discount_amount: number;
  total_amount: number;
  currency: string;
  
  // Payment Information
  payment_method?: POSPaymentMethod;
  payment_status?: POSPaymentStatus;
  
  // Transaction Timing
  transaction_date: string;
  pos_created_at: string;
  pos_updated_at?: string;
  
  // Location & Staff
  location_id?: string;
  location_name?: string;
  staff_id?: string;
  staff_name?: string;
  
  // Customer Information
  customer_id?: string;
  customer_email?: string;
  customer_phone?: string;
  
  // Order Context
  order_type?: POSOrderType;
  table_number?: string;
  receipt_number?: string;
  
  // Sync Status
  is_synced_to_sales: boolean;
  sales_record_id?: string;
  sync_attempted_at?: string;
  sync_completed_at?: string;
  sync_error?: string;
  sync_retry_count: number;
  
  // Raw Data
  raw_data?: Record<string, any>;
  
  // Processing Status
  is_processed: boolean;
  processing_error?: string;
  
  // Duplicate Detection
  is_duplicate: boolean;
  duplicate_of?: string;
  
  // Timestamps
  created_at: string;
  updated_at: string;
  
  // Related Items
  items?: POSTransactionItem[];
}

export interface POSTransactionItem {
  // Primary identifiers
  id: string;
  transaction_id: string;
  tenant_id: string;
  
  // POS Item Information
  external_item_id?: string;
  sku?: string;
  
  // Product Details
  product_name: string;
  product_category?: string;
  product_subcategory?: string;
  
  // Quantity & Pricing
  quantity: number;
  unit_price: number;
  total_price: number;
  
  // Discounts & Modifiers
  discount_amount: number;
  tax_amount: number;
  
  // Modifiers (e.g., extra shot, no foam for coffee)
  modifiers?: Record<string, any>;
  
  // Inventory Mapping
  inventory_product_id?: string;
  is_mapped_to_inventory: boolean;
  
  // Sync Status
  is_synced_to_sales: boolean;
  sync_error?: string;
  
  // Raw Data
  raw_data?: Record<string, any>;
  
  // Timestamps
  created_at: string;
  updated_at: string;
}

// ============================================================================
// POS WEBHOOK LOGS
// ============================================================================

export interface POSWebhookLog {
  // Primary identifiers
  id: string;
  tenant_id?: string;
  
  // POS Provider Information
  pos_system: POSSystem;
  webhook_type: string;
  
  // Request Information
  method: string;
  url_path: string;
  query_params?: Record<string, any>;
  headers?: Record<string, any>;
  
  // Payload
  raw_payload: string;
  payload_size: number;
  content_type?: string;
  
  // Security
  signature?: string;
  is_signature_valid?: boolean;
  source_ip?: string;
  
  // Processing Status
  status: POSWebhookStatus;
  processing_started_at?: string;
  processing_completed_at?: string;
  processing_duration_ms?: number;
  
  // Error Handling
  error_message?: string;
  error_code?: string;
  retry_count: number;
  max_retries: number;
  
  // Response Information
  response_status_code?: number;
  response_body?: string;
  response_sent_at?: string;
  
  // Event Metadata
  event_id?: string;
  event_timestamp?: string;
  sequence_number?: number;
  
  // Business Data References
  transaction_id?: string;
  order_id?: string;
  customer_id?: string;
  
  // Internal References
  created_transaction_id?: string;
  updated_transaction_id?: string;
  
  // Duplicate Detection
  is_duplicate: boolean;
  duplicate_of?: string;
  
  // Processing Priority
  priority: string;
  
  // Debugging Information
  user_agent?: string;
  forwarded_for?: string;
  request_id?: string;
  
  // Timestamps
  received_at: string;
  created_at: string;
  updated_at: string;
}

// ============================================================================
// POS SYNC LOGS
// ============================================================================

export interface POSSyncLog {
  // Primary identifiers
  id: string;
  tenant_id: string;
  pos_config_id: string;
  
  // Sync Operation Details
  sync_type: POSSyncType;
  sync_direction: POSSyncDirection;
  data_type: POSDataType;
  
  // POS Provider Information
  pos_system: POSSystem;
  
  // Sync Status
  status: string; // started, in_progress, completed, failed, cancelled
  
  // Timing Information
  started_at: string;
  completed_at?: string;
  duration_seconds?: number;
  
  // Date Range for Sync
  sync_from_date?: string;
  sync_to_date?: string;
  
  // Statistics
  records_requested: number;
  records_processed: number;
  records_created: number;
  records_updated: number;
  records_skipped: number;
  records_failed: number;
  
  // API Usage Statistics
  api_calls_made: number;
  api_rate_limit_hits: number;
  total_api_time_ms: number;
  
  // Error Information
  error_message?: string;
  error_code?: string;
  error_details?: Record<string, any>;
  
  // Retry Information
  retry_attempt: number;
  max_retries: number;
  parent_sync_id?: string;
  
  // Configuration Snapshot
  sync_configuration?: Record<string, any>;
  
  // Progress Tracking
  current_page?: number;
  total_pages?: number;
  current_batch?: number;
  total_batches?: number;
  progress_percentage?: number;
  
  // Data Quality
  validation_errors?: Record<string, any>[];
  data_quality_score?: number;
  
  // Performance Metrics
  memory_usage_mb?: number;
  cpu_usage_percentage?: number;
  network_bytes_received?: number;
  network_bytes_sent?: number;
  
  // Business Impact
  revenue_synced?: number;
  transactions_synced: number;
  
  // Trigger Information
  triggered_by?: string; // system, user, webhook, schedule
  triggered_by_user_id?: string;
  trigger_details?: Record<string, any>;
  
  // External References
  external_batch_id?: string;
  webhook_log_id?: string;
  
  // Timestamps
  created_at: string;
  updated_at: string;
  
  // Metadata
  notes?: string;
  tags?: string[];
}

// ============================================================================
// SUPPORTED POS SYSTEMS
// ============================================================================

export interface POSSystemInfo {
  id: POSSystem;
  name: string;
  description: string;
  features: string[];
  supported_regions: string[];
}

export interface POSCredentialsField {
  field: string;
  label: string;
  type: 'text' | 'password' | 'url' | 'select';
  placeholder?: string;
  required: boolean;
  help_text?: string;
  options?: { value: string; label: string }[];
}

export interface POSProviderConfig {
  id: POSSystem;
  name: string;
  logo: string;
  description: string;
  features: string[];
  required_fields: POSCredentialsField[];
}

// ============================================================================
// SYNC ANALYTICS & PERFORMANCE TYPES
// ============================================================================

export interface SyncHealth {
  status: string;
  success_rate: number;
  average_duration_minutes: number;
  last_error?: string;
}

export interface SyncFrequency {
  daily_average: number;
  peak_day?: string;
  peak_count: number;
}

export interface ErrorAnalysis {
  common_errors: any[];
  error_trends: any[];
}

export interface SyncAnalytics {
  period_days: number;
  total_syncs: number;
  successful_syncs: number;
  failed_syncs: number;
  success_rate: number;
  average_duration_minutes: number;
  total_transactions_synced: number;
  total_revenue_synced: number;
  sync_frequency: SyncFrequency;
  error_analysis: ErrorAnalysis;
}

export interface TransactionSummary {
  total_amount: number;
  transaction_count: number;
  sync_status: {
    synced: number;
    pending: number;
    failed: number;
  };
}

// ============================================================================
// WEBHOOK TYPES
// ============================================================================

export interface WebhookSupportedEvents {
  events: string[];
  format: string;
  authentication: string;
}

export interface WebhookStatus {
  pos_system: string;
  status: string;
  endpoint: string;
  supported_events: WebhookSupportedEvents;
  last_received?: string;
  total_received: number;
}

// ============================================================================
// BASE POS CLIENT TYPES (matching backend integrations)
// ============================================================================

export interface POSCredentialsData {
  pos_system: POSSystem;
  environment: POSEnvironment;
  api_key?: string;
  api_secret?: string;
  access_token?: string;
  application_id?: string;
  merchant_id?: string;
  location_id?: string;
  webhook_secret?: string;
  additional_params?: Record<string, any>;
}

export interface ClientPOSTransaction {
  external_id: string;
  transaction_type: string;
  status: string;
  total_amount: number;
  subtotal: number;
  tax_amount: number;
  tip_amount: number;
  discount_amount: number;
  currency: string;
  transaction_date: string;
  payment_method?: string;
  payment_status?: string;
  location_id?: string;
  location_name?: string;
  staff_id?: string;
  staff_name?: string;
  customer_id?: string;
  customer_email?: string;
  order_type?: string;
  table_number?: string;
  receipt_number?: string;
  external_order_id?: string;
  items: ClientPOSTransactionItem[];
  raw_data: Record<string, any>;
}

export interface ClientPOSTransactionItem {
  external_id?: string;
  sku?: string;
  name: string;
  category?: string;
  quantity: number;
  unit_price: number;
  total_price: number;
  discount_amount: number;
  tax_amount: number;
  modifiers?: Record<string, any>;
  raw_data?: Record<string, any>;
}

export interface ClientPOSProduct {
  external_id: string;
  name: string;
  sku?: string;
  category?: string;
  subcategory?: string;
  price: number;
  description?: string;
  is_active: boolean;
  raw_data: Record<string, any>;
}

export interface SyncResult {
  success: boolean;
  records_processed: number;
  records_created: number;
  records_updated: number;
  records_skipped: number;
  records_failed: number;
  errors: string[];
  warnings: string[];
  duration_seconds: number;
  api_calls_made: number;
}

// ============================================================================
// API REQUEST/RESPONSE TYPES
// ============================================================================

// GET /tenants/{tenant_id}/pos/configurations
export interface GetPOSConfigurationsRequest {
  tenant_id: string;
  pos_system?: POSSystem;
  is_active?: boolean;
}

export interface GetPOSConfigurationsResponse {
  configurations: POSConfiguration[];
  total: number;
  supported_systems: POSSystem[];
}

// POST /tenants/{tenant_id}/pos/configurations
export interface CreatePOSConfigurationRequest {
  tenant_id: string;
  pos_system: POSSystem;
  provider_name: string;
  environment: POSEnvironment;
  credentials: Record<string, any>;
  sync_settings?: {
    auto_sync_enabled: boolean;
    sync_interval_minutes: number;
    sync_sales: boolean;
    sync_inventory: boolean;
    sync_customers: boolean;
  };
  webhook_url?: string;
  location_id?: string;
  merchant_id?: string;
  notes?: string;
}

export interface CreatePOSConfigurationResponse {
  message: string;
  id: string;
  configuration?: POSConfiguration;
}

// GET /tenants/{tenant_id}/pos/configurations/{config_id}
export interface GetPOSConfigurationRequest {
  tenant_id: string;
  config_id: string;
}

export interface GetPOSConfigurationResponse {
  configuration: POSConfiguration;
}

// PUT /tenants/{tenant_id}/pos/configurations/{config_id}
export interface UpdatePOSConfigurationRequest {
  tenant_id: string;
  config_id: string;
  provider_name?: string;
  credentials?: Record<string, any>;
  sync_settings?: {
    auto_sync_enabled?: boolean;
    sync_interval_minutes?: number;
    sync_sales?: boolean;
    sync_inventory?: boolean;
    sync_customers?: boolean;
  };
  webhook_url?: string;
  location_id?: string;
  merchant_id?: string;
  notes?: string;
  is_active?: boolean;
}

export interface UpdatePOSConfigurationResponse {
  message: string;
  configuration?: POSConfiguration;
}

// DELETE /tenants/{tenant_id}/pos/configurations/{config_id}
export interface DeletePOSConfigurationRequest {
  tenant_id: string;
  config_id: string;
}

export interface DeletePOSConfigurationResponse {
  message: string;
  success: boolean;
}

// POST /tenants/{tenant_id}/pos/configurations/{config_id}/test-connection
export interface TestPOSConnectionRequest {
  tenant_id: string;
  config_id: string;
}

export interface TestPOSConnectionResponse {
  success: boolean;
  message: string;
  tested_at: string;
}

// GET /pos/supported-systems
export interface GetSupportedPOSSystemsResponse {
  systems: POSSystemInfo[];
}

// ============================================================================
// UTILITY TYPES
// ============================================================================

export interface POSApiError {
  message: string;
  status?: number;
  code?: string;
  details?: any;
}

export interface POSSyncSettings {
  auto_sync_enabled: boolean;
  sync_interval_minutes: number;
  sync_sales: boolean;
  sync_inventory: boolean;
  sync_customers: boolean;
}

export interface POSConnectionTestResult {
  success: boolean;
  message: string;
  tested_at: string;
}

// For backward compatibility with existing BakeryConfigPage
export type { POSProviderConfig, POSSyncSettings as SyncSettings };