export * from './catalog';

// ==============================================================================
// MULTI-MERCHANT DATABASE TYPES & MODELS
// ==============================================================================

export type ShopStatus = 'installed' | 'uninstalled' | 'suspended';

export type PlanTier = 'basic' | 'growth' | 'scale' | 'accelerate' | 'free' | 'custom' | string;

export interface PricingPlan {
  id: string; // 'basic' | 'growth' | 'scale' | 'accelerate'
  name: string; // 'Basic Plan', 'Growth Plan', 'Scale Plan'
  description?: string | null;
  price: number; // monthly price, e.g. 0, 13, 99
  yearly_price?: number; // e.g. 0, 124.80, 950.40
  currency?: string; // 'USD'
  interval: 'month' | 'year';
  yearly_discount_label?: string | null; // e.g. 'Save 20%'
  display_order?: number;
  is_visible?: boolean;
  sku_limit: number | null; // e.g. 100, 5000, null for Unlimited
  campaigns_limit: number | null; // e.g. 1, 3, null for Unlimited
  trial_days?: number; // e.g. 14 or 7 days free trial
  capi_enabled: boolean;
  supplementary_feeds: boolean;
  custom_titles: boolean;
  website_audit: boolean;
  dedicated_manager: boolean;
  support: string;
  features: string[];
  badge?: string | null; // e.g. "Free", "Most Popular", "Scale & Enterprise"
  is_active: boolean;
  feature_flags?: Record<string, boolean>;
  feature_limits?: Record<string, number | null>;
  created_at?: string;
  updated_at?: string;
}

export interface FeatureDefinition {
  id: string; // e.g. 'meta.pixel_count', 'meta.capi_tracking', etc.
  name: string; // Display label
  description?: string | null;
  display_order: number;
  is_visible: boolean;
  category?: string;
  basic_value: string;
  growth_value: string;
  scale_value: string;
  basic_enabled: boolean;
  growth_enabled: boolean;
  scale_enabled: boolean;
  basic_limit?: number | null;
  growth_limit?: number | null;
  scale_limit?: number | null;
  created_at?: string;
  updated_at?: string;
}

export interface ShopRecord {
  id: string;
  shopify_domain: string; // e.g. "my-brand.myshopify.com"
  shopify_shop_id?: string;
  shop_name?: string | null;
  owner_email?: string | null;
  owner_name?: string | null;
  country?: string | null;
  currency?: string | null;
  billing_cycle?: 'monthly' | 'yearly';
  monthly_revenue?: number;
  last_active_at?: string | null;
  access_token_encrypted: string; // AES-256-GCM encrypted
  refresh_token_encrypted?: string | null;
  token_expires_at?: string | null;
  scopes: string[];
  installed_at: string;
  uninstalled_at?: string | null;
  status: ShopStatus;
  plan: PlanTier;
  plan_custom_sku_limit?: number | null;
  subscription_id?: string | null;
  subscription_status?: 'active' | 'pending' | 'cancelled' | 'trial' | 'free';
  trial_days?: number;
  trial_starts_at?: string | null;
  trial_ends_at?: string | null;
  current_period_end?: string | null;
  created_at: string;
  updated_at: string;
}

export type AdminRole = 'super_admin' | 'billing_admin' | 'support_agent';

export interface AdminUserRecord {
  id: string;
  email: string;
  password_hash: string;
  name: string;
  role: AdminRole;
  avatar_url?: string | null;
  is_active: boolean;
  last_login_at?: string | null;
  created_at: string;
  updated_at: string;
}

export interface AppInstallationRecord {
  id: string;
  shop_id: string;
  shopify_domain: string;
  event_type: 'installed' | 'uninstalled' | 'reinstalled';
  plan_at_time?: string;
  metadata?: Record<string, unknown> | null;
  occurred_at: string;
  created_at: string;
}

export interface SubscriptionRecord {
  id: string;
  shop_id: string;
  shopify_domain: string;
  shopify_subscription_id?: string | null;
  plan_id: string;
  plan_name: string;
  status: 'active' | 'trial' | 'cancelled' | 'past_due' | 'free' | 'pending' | 'expired';
  billing_cycle: 'monthly' | 'yearly';
  price: number;
  currency: string;
  trial_days: number;
  trial_starts_at?: string | null;
  trial_ends_at?: string | null;
  current_period_start?: string | null;
  current_period_end?: string | null;
  cancelled_at?: string | null;
  created_at: string;
  updated_at: string;
}

export interface BillingEventRecord {
  id: string;
  shop_id: string;
  shopify_domain: string;
  subscription_id?: string | null;
  event_type: 'charge_created' | 'charge_activated' | 'charge_cancelled' | 'payment_success' | 'payment_failed' | 'refund';
  amount: number;
  currency: string;
  status: 'verified' | 'pending' | 'failed';
  shopify_charge_id?: string | null;
  details?: Record<string, unknown> | null;
  billing_date: string;
  created_at: string;
}

export interface StoreActivityLogRecord {
  id: string;
  shop_id: string;
  shopify_domain: string;
  action: string;
  actor: string;
  description: string;
  metadata?: Record<string, unknown> | null;
  created_at: string;
}

export type PixelType = 'master' | 'collection' | 'tag' | 'backup';

export interface MetaPixelRecord {
  id: string;
  shop_id: string;
  pixel_name: string;
  pixel_id: string;
  pixel_type: PixelType;
  source?: 'manual' | 'auto';
  facebook_account_id?: string | null;
  target_collection?: string | null;
  target_tag?: string | null;
  access_token_encrypted?: string | null;
  test_event_code?: string | null;
  capi_enabled: boolean;
  capi_status?: 'not_configured' | 'active' | 'paused' | 'error';
  pages_config?: string;
  emq_score?: number;
  events_count_24h?: number;
  status: 'active' | 'paused' | 'error';
  verification_status?: 'unverified' | 'verifying' | 'verified' | 'failed';
  is_active?: boolean;
  app_embed_active?: boolean;
  created_at: string;
  updated_at: string;
}

export type MetaConnectionStatus = 'connected' | 'disconnected' | 'token_expired' | 'error';

export interface MetaConnectionRecord {
  id: string;
  shop_id: string;
  fb_user_id?: string | null;
  fb_user_name?: string | null;
  business_id?: string | null;
  business_name?: string | null;
  catalog_id?: string | null;
  catalog_name?: string | null;
  pixel_id?: string | null;
  pixel_name?: string | null;
  access_token_encrypted: string; // AES-256-GCM encrypted
  test_event_code?: string | null;
  token_expires_at?: string | null;
  status: MetaConnectionStatus;
  connected_at?: string | null;
  onboarding_completed?: boolean;
  created_at: string;
  updated_at: string;
}

export interface AppConfigurationRecord {
  id: string;
  shop_id: string;
  shopify_domain: string;
  shopify_access_token_encrypted?: string | null;
  shopify_api_key?: string | null;
  shopify_api_secret_encrypted?: string | null;
  shopify_api_version?: string;
  meta_business_id?: string | null;
  meta_business_name?: string | null;
  meta_catalog_id?: string | null;
  meta_catalog_name?: string | null;
  meta_pixel_id?: string | null;
  meta_pixel_name?: string | null;
  meta_access_token_encrypted?: string | null;
  meta_test_event_code?: string | null;
  created_at: string;
  updated_at: string;
}

export type SyncType = 'feed' | 'batch_api' | 'webhook';
export type SyncStatus = 'pending' | 'processing' | 'completed' | 'failed';

export interface CatalogSyncRecord {
  id: string;
  shop_id: string;
  sync_type: SyncType;
  status: SyncStatus;
  total_products: number;
  processed_products: number;
  failed_products: number;
  warning_count: number;
  started_at: string;
  completed_at?: string | null;
  error_message?: string | null;
  details?: Record<string, unknown>;
  created_at?: string;
  updated_at?: string;
}

export interface CatalogProductRecord {
  id: string;
  shop_id: string;
  shopify_product_id: string;
  shopify_variant_id: string;
  meta_product_id?: string | null;
  sku?: string | null;
  barcode?: string | null;
  title: string;
  variant_title?: string | null;
  description: string;
  price: number;
  compare_at_price?: number | null;
  currency: string;
  availability: 'in stock' | 'out of stock' | 'preorder' | 'available for order';
  inventory_quantity: number;
  image_url: string;
  additional_images?: string[];
  video_url?: string | null;
  product_url: string;
  weight?: number | null;
  weight_unit?: string | null;
  body_html?: string | null;
  google_product_category?: string | null;
  fb_product_category?: string | null;
  brand: string;
  condition: 'new' | 'refurbished' | 'used';
  custom_label_0?: string | null;
  custom_label_1?: string | null;
  custom_label_2?: string | null;
  custom_label_3?: string | null;
  custom_label_4?: string | null;
  status: 'synced' | 'warning' | 'error';
  sync_error?: string | null;
  last_synced_at: string;
  is_excluded?: boolean;
  exclusion_reason?: string | null;
  excluded_at?: string | null;
  tags?: string[] | null;
  collections?: string[] | null;
  collection_ids?: string[] | null;
  vendor?: string | null;
  product_type?: string | null;
  created_at?: string;
  updated_at?: string;
}

export type CapiStatus = 'sent' | 'failed' | 'deduplicated';

export interface CapiEventRecord {
  id: string;
  shop_id: string;
  event_id: string;
  event_name: 'PageView' | 'ViewContent' | 'AddToCart' | 'InitiateCheckout' | 'Purchase' | 'Search' | 'AddPaymentInfo' | string;
  event_source_url?: string | null;
  shopify_order_id?: string | null;
  payload_hash: string;
  user_data_masked: Record<string, string>;
  custom_data?: Record<string, unknown>;
  status: CapiStatus;
  meta_event_id?: string | null;
  response_code: number;
  response_body?: Record<string, unknown> | null;
  error_message?: string | null;
  duration_ms: number;
  created_at: string;
  updated_at?: string;
}

export interface WebhookEventRecord {
  id: string;
  shop_id: string;
  topic: string;
  shopify_webhook_id: string;
  payload_json: string;
  status: 'queued' | 'processed' | 'failed';
  attempts: number;
  error_message?: string | null;
  created_at: string;
  processed_at?: string | null;
  updated_at?: string;
}

export interface AuditLogRecord {
  id: string;
  shop_id: string;
  action: string;
  actor: 'merchant' | 'system' | 'shopify_webhook' | 'worker';
  metadata?: Record<string, unknown>;
  created_at: string;
  updated_at?: string;
}

// ==============================================================================
// META GRAPH API & CAPI TYPES
// ==============================================================================

export interface MetaUserData {
  em?: string[]; // SHA-256 hashed emails
  ph?: string[]; // SHA-256 hashed phone numbers
  fn?: string[]; // SHA-256 hashed first names
  ln?: string[]; // SHA-256 hashed last names
  ct?: string[]; // SHA-256 hashed city
  zp?: string[]; // SHA-256 hashed zip
  country?: string[]; // SHA-256 hashed 2-letter country code
  client_ip_address?: string;
  client_user_agent?: string;
  fbc?: string;
  fbp?: string;
  external_id?: string[];
}

export interface MetaCustomData {
  currency?: string;
  value?: number;
  content_name?: string;
  content_category?: string;
  content_ids?: string[];
  content_type?: 'product' | 'product_group';
  contents?: Array<{
    id: string;
    quantity: number;
    item_price?: number;
    title?: string;
    brand?: string;
    category?: string;
  }>;
  num_items?: number;
  order_id?: string;
  search_string?: string;
  status?: string;
  [key: string]: unknown;
}

export interface MetaServerEvent {
  event_name: string;
  event_time: number;
  event_id: string;
  event_source_url?: string;
  action_source: 'website' | 'system_generated' | 'app';
  user_data: MetaUserData;
  custom_data?: MetaCustomData;
  opt_out?: boolean;
}

export interface MetaCapiPayload {
  data: MetaServerEvent[];
  test_event_code?: string;
  partner_agent?: string;
}

// ==============================================================================
// ASYNCHRONOUS JOB QUEUE TYPES
// ==============================================================================

export type JobType = 'catalog_sync' | 'webhook_process' | 'capi_dispatch' | 'gdpr_cleanup';

export interface BaseJob<T = Record<string, unknown>> {
  id: string;
  type: JobType;
  shop_id: string;
  payload: T;
  priority: number;
  attempts: number;
  max_attempts: number;
  status: 'queued' | 'running' | 'completed' | 'failed';
  error?: string;
  created_at: string;
  updated_at: string;
  run_at: string;
}

export interface CatalogSyncJobPayload {
  sync_id: string;
  shop_domain: string;
  force_full?: boolean;
}

export interface WebhookJobPayload {
  webhook_event_id: string;
  topic: string;
  body: Record<string, unknown>;
}

// ==============================================================================
// SYSTEM BRANDING & DYNAMIC IDENTITY TYPES
// ==============================================================================

export interface SystemBrandingRecord {
  id: string; // 'default_branding'
  app_name: string; // e.g. "DigiPixora — Meta Pixel & Ads"
  logo_url: string | null;
  favicon_url: string | null;
  created_at: string;
  updated_at: string;
  updated_by: string;
}

export interface BrandingConfig {
  appName: string;
  logoUrl: string | null;
  faviconUrl: string | null;
  updatedAt?: string;
  updatedBy?: string;
}

