// Database schema and collection structure for Firebase Firestore
import { 
  collection, 
  doc, 
  CollectionReference, 
  DocumentReference 
} from 'firebase/firestore';
import { db } from '../firebase';
import { COLLECTIONS } from './types';
import type {
  ShopProfileDB,
  UserDB,
  CustomerDB,
  CustomerMeasurementDB,
  InventoryItemDB,
  TailoringItemDB,
  EmployeeDB,
  OrderDB,
  IncomeTransactionDB,
  ExpenseTransactionDB,
  AppearanceSettingsDB,
  NotificationSettingsDB,
  AuditLogDB,
  ReportDataDB,
} from './types';

// Collection references with proper typing
export const shopsCollection = collection(db, COLLECTIONS.SHOPS) as CollectionReference<ShopProfileDB>;
export const usersCollection = collection(db, COLLECTIONS.USERS) as CollectionReference<UserDB>;
export const customersCollection = collection(db, COLLECTIONS.CUSTOMERS) as CollectionReference<CustomerDB>;
export const customerMeasurementsCollection = collection(db, COLLECTIONS.CUSTOMER_MEASUREMENTS) as CollectionReference<CustomerMeasurementDB>;
export const inventoryCollection = collection(db, COLLECTIONS.INVENTORY) as CollectionReference<InventoryItemDB>;
export const tailoringItemsCollection = collection(db, COLLECTIONS.TAILORING_ITEMS) as CollectionReference<TailoringItemDB>;
export const employeesCollection = collection(db, COLLECTIONS.EMPLOYEES) as CollectionReference<EmployeeDB>;
export const ordersCollection = collection(db, COLLECTIONS.ORDERS) as CollectionReference<OrderDB>;
export const incomeTransactionsCollection = collection(db, COLLECTIONS.INCOME_TRANSACTIONS) as CollectionReference<IncomeTransactionDB>;
export const expenseTransactionsCollection = collection(db, COLLECTIONS.EXPENSE_TRANSACTIONS) as CollectionReference<ExpenseTransactionDB>;
export const appearanceSettingsCollection = collection(db, COLLECTIONS.APPEARANCE_SETTINGS) as CollectionReference<AppearanceSettingsDB>;
export const notificationSettingsCollection = collection(db, COLLECTIONS.NOTIFICATION_SETTINGS) as CollectionReference<NotificationSettingsDB>;
export const auditLogsCollection = collection(db, COLLECTIONS.AUDIT_LOGS) as CollectionReference<AuditLogDB>;
export const reportDataCollection = collection(db, COLLECTIONS.REPORT_DATA) as CollectionReference<ReportDataDB>;

// Document reference helpers
export const getShopDoc = (shopId: string): DocumentReference<ShopProfileDB> => 
  doc(shopsCollection, shopId);

export const getUserDoc = (userId: string): DocumentReference<UserDB> => 
  doc(usersCollection, userId);

export const getCustomerDoc = (customerId: string): DocumentReference<CustomerDB> => 
  doc(customersCollection, customerId);

export const getCustomerMeasurementDoc = (measurementId: string): DocumentReference<CustomerMeasurementDB> => 
  doc(customerMeasurementsCollection, measurementId);

export const getInventoryDoc = (inventoryId: string): DocumentReference<InventoryItemDB> => 
  doc(inventoryCollection, inventoryId);

export const getTailoringItemDoc = (itemId: string): DocumentReference<TailoringItemDB> => 
  doc(tailoringItemsCollection, itemId);

export const getEmployeeDoc = (employeeId: string): DocumentReference<EmployeeDB> => 
  doc(employeesCollection, employeeId);

export const getOrderDoc = (orderId: string): DocumentReference<OrderDB> => 
  doc(ordersCollection, orderId);

export const getIncomeTransactionDoc = (transactionId: string): DocumentReference<IncomeTransactionDB> => 
  doc(incomeTransactionsCollection, transactionId);

export const getExpenseTransactionDoc = (transactionId: string): DocumentReference<ExpenseTransactionDB> => 
  doc(expenseTransactionsCollection, transactionId);

export const getAppearanceSettingsDoc = (settingsId: string): DocumentReference<AppearanceSettingsDB> => 
  doc(appearanceSettingsCollection, settingsId);

export const getNotificationSettingsDoc = (settingsId: string): DocumentReference<NotificationSettingsDB> => 
  doc(notificationSettingsCollection, settingsId);

export const getAuditLogDoc = (logId: string): DocumentReference<AuditLogDB> => 
  doc(auditLogsCollection, logId);

export const getReportDataDoc = (reportId: string): DocumentReference<ReportDataDB> => 
  doc(reportDataCollection, reportId);

// Database schema documentation
export const DATABASE_SCHEMA = {
  // Root collections
  shops: {
    description: 'Shop profiles and basic information',
    fields: {
      id: 'string (document ID)',
      shopName: 'string',
      email: 'string',
      address: 'string',
      contact: 'string',
      logoUrl: 'string (optional)',
      ownerId: 'string (user ID)',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'ownerId',
      'email',
      'createdAt',
    ],
  },
  
  users: {
    description: 'User accounts and authentication data',
    fields: {
      id: 'string (document ID, matches auth UID)',
      email: 'string',
      displayName: 'string (optional)',
      photoURL: 'string (optional)',
      role: 'string (owner|manager|employee)',
      shopId: 'string',
      isActive: 'boolean',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'email',
      'shopId',
      'role',
      'isActive',
    ],
  },
  
  customers: {
    description: 'Customer information and contact details',
    fields: {
      id: 'string (document ID)',
      name: 'string',
      phone: 'string',
      email: 'string (optional)',
      address: 'string (optional)',
      shopId: 'string',
      totalOrders: 'number',
      totalSpent: 'number',
      lastOrderDate: 'timestamp (optional)',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
      'phone',
      'name',
      'totalSpent',
      'lastOrderDate',
    ],
  },
  
  customerMeasurements: {
    description: 'Customer measurements for different items',
    fields: {
      id: 'string (document ID)',
      customerId: 'string',
      itemName: 'string',
      measurements: 'string (JSON or formatted text)',
      shopId: 'string',
      notes: 'string (optional)',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'customerId',
      'shopId',
      'itemName',
    ],
  },
  
  inventory: {
    description: 'Fabric and material inventory',
    fields: {
      id: 'string (document ID)',
      name: 'string',
      type: 'string (Cotton|Silk|Wool|Linen)',
      color: 'string',
      pricePerMeter: 'number',
      quantity: 'number',
      lowStockThreshold: 'number',
      shopId: 'string',
      supplier: 'string (optional)',
      purchaseDate: 'timestamp (optional)',
      expiryDate: 'timestamp (optional)',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
      'type',
      'quantity',
      'lowStockThreshold',
    ],
  },
  
  tailoringItems: {
    description: 'Available tailoring services and items',
    fields: {
      id: 'string (document ID)',
      name: 'string',
      category: 'string (Men|Women|Kids|Other)',
      sewingPrice: 'number',
      artisanWage: 'number',
      shopId: 'string',
      description: 'string (optional)',
      estimatedTime: 'number (optional, in hours)',
      isActive: 'boolean',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
      'category',
      'isActive',
      'sewingPrice',
    ],
  },
  
  employees: {
    description: 'Employee information and roles',
    fields: {
      id: 'string (document ID)',
      name: 'string',
      phone: 'string',
      email: 'string (optional)',
      role: 'string (Tailor|Manager|Cutter|Assistant)',
      monthlySalary: 'number (optional)',
      shopId: 'string',
      hireDate: 'timestamp',
      isActive: 'boolean',
      address: 'string (optional)',
      emergencyContact: 'string (optional)',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
      'role',
      'isActive',
      'hireDate',
    ],
  },
  
  orders: {
    description: 'Customer orders and their details',
    fields: {
      id: 'string (document ID)',
      memoId: 'string (optional)',
      customerId: 'string',
      customerName: 'string (denormalized)',
      customerPhone: 'string (denormalized)',
      type: 'string (pickup|delivery)',
      status: 'string (New|In Progress|Ready for Delivery|Delivered|Completed|Cancelled)',
      orderDate: 'timestamp',
      totalAmount: 'number',
      paidAmount: 'number',
      totalArtisanWage: 'number',
      items: 'array of OrderItemDB',
      deliveryDate: 'timestamp (optional)',
      deliveryAddress: 'string (optional)',
      artisanId: 'string (optional)',
      artisanName: 'string (optional, denormalized)',
      cuttingMasterId: 'string (optional)',
      cuttingMasterName: 'string (optional, denormalized)',
      artisanAssignedDate: 'timestamp (optional)',
      artisanCompletedDate: 'timestamp (optional)',
      cuttingCompletedDate: 'timestamp (optional)',
      shopId: 'string',
      notes: 'string (optional)',
      priority: 'string (low|medium|high)',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
      'customerId',
      'status',
      'orderDate',
      'deliveryDate',
      'artisanId',
      'cuttingMasterId',
      'priority',
    ],
  },
  
  incomeTransactions: {
    description: 'Income and revenue transactions',
    fields: {
      id: 'string (document ID)',
      category: 'string',
      amount: 'number',
      description: 'string',
      transactionDate: 'timestamp',
      shopId: 'string',
      orderId: 'string (optional)',
      paymentMethod: 'string (cash|card|upi|bank_transfer|other)',
      isEditable: 'boolean',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
      'transactionDate',
      'category',
      'orderId',
      'paymentMethod',
    ],
  },
  
  expenseTransactions: {
    description: 'Expense and cost transactions',
    fields: {
      id: 'string (document ID)',
      category: 'string',
      amount: 'number',
      description: 'string (optional)',
      person: 'string (optional)',
      transactionDate: 'timestamp',
      shopId: 'string',
      employeeId: 'string (optional)',
      receiptUrl: 'string (optional)',
      isEditable: 'boolean',
      paymentMethod: 'string (cash|card|upi|bank_transfer|other)',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
      'transactionDate',
      'category',
      'employeeId',
      'paymentMethod',
    ],
  },
  
  appearanceSettings: {
    description: 'User interface appearance preferences',
    fields: {
      id: 'string (document ID)',
      theme: 'string (light|dark)',
      font: 'string (inter|manrope|system|poppins|pt-sans)',
      shopId: 'string',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
    ],
  },
  
  notificationSettings: {
    description: 'SMS and WhatsApp notification configuration',
    fields: {
      id: 'string (document ID)',
      smsEnabled: 'boolean',
      smsProvider: 'string (twilio|other)',
      smsApiKey: 'string (optional)',
      smsApiSecret: 'string (optional)',
      smsSenderId: 'string (optional)',
      smsMessageTemplate: 'string (optional)',
      whatsappEnabled: 'boolean',
      whatsappApiKey: 'string (optional)',
      whatsappSenderNumber: 'string (optional)',
      whatsappMessageTemplate: 'string (optional)',
      shopId: 'string',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
    ],
  },
  
  auditLogs: {
    description: 'Audit trail for all database changes',
    fields: {
      id: 'string (document ID)',
      action: 'string (create|update|delete)',
      entityType: 'string',
      entityId: 'string',
      userId: 'string',
      userName: 'string',
      changes: 'object (optional)',
      shopId: 'string',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
      'entityType',
      'entityId',
      'userId',
      'createdAt',
    ],
  },
  
  reportData: {
    description: 'Cached report data for performance',
    fields: {
      id: 'string (document ID)',
      reportType: 'string (daily|weekly|monthly|yearly)',
      startDate: 'timestamp',
      endDate: 'timestamp',
      totalIncome: 'number',
      totalExpenses: 'number',
      netProfit: 'number',
      orderCount: 'number',
      customerCount: 'number',
      shopId: 'string',
      data: 'object (flexible structure)',
      createdAt: 'timestamp',
      updatedAt: 'timestamp',
    },
    indexes: [
      'shopId',
      'reportType',
      'startDate',
      'endDate',
    ],
  },
} as const;
