// Database types and interfaces for Firebase Firestore
import { Timestamp } from 'firebase/firestore';

// Base interface for all database documents
export interface BaseDocument {
  id: string;
  createdAt: Timestamp;
  updatedAt: Timestamp;
}

// Shop Profile
export interface ShopProfileDB extends BaseDocument {
  shopName: string;
  email: string;
  address: string;
  contact: string;
  logoUrl?: string | null;
  ownerId: string; // User ID of the shop owner
}

// User/Authentication
export interface UserDB extends BaseDocument {
  email: string;
  displayName?: string;
  photoURL?: string;
  role: 'owner' | 'manager' | 'employee';
  shopId: string;
  isActive: boolean;
}

// Customer
export interface CustomerDB extends BaseDocument {
  name: string;
  phone: string;
  email?: string;
  address?: string;
  shopId: string;
  totalOrders: number;
  totalSpent: number;
  lastOrderDate?: Timestamp;
}

// Customer Measurements
export interface CustomerMeasurementDB extends BaseDocument {
  customerId: string;
  itemName: string;
  measurements: string;
  shopId: string;
  notes?: string;
}

// Inventory Item
export interface InventoryItemDB extends BaseDocument {
  name: string;
  type: 'Cotton' | 'Silk' | 'Wool' | 'Linen';
  color: string;
  pricePerMeter: number;
  quantity: number;
  lowStockThreshold: number;
  shopId: string;
  supplier?: string;
  purchaseDate?: Timestamp;
  expiryDate?: Timestamp;
}

// Tailoring Item/Service
export interface TailoringItemDB extends BaseDocument {
  name: string;
  category: 'Men' | 'Women' | 'Kids' | 'Other';
  sewingPrice: number;
  artisanWage: number;
  shopId: string;
  description?: string;
  estimatedTime?: number; // in hours
  isActive: boolean;
}

// Employee
export interface EmployeeDB extends BaseDocument {
  name: string;
  phone: string;
  email?: string;
  role: 'Tailor' | 'Manager' | 'Cutter' | 'Assistant';
  monthlySalary?: number;
  shopId: string;
  hireDate: Timestamp;
  isActive: boolean;
  address?: string;
  emergencyContact?: string;
}

// Order Item
export interface OrderItemDB {
  id: string;
  name: string;
  quantity: number;
  price: number;
  artisanWage: number;
  measurements?: string;
  fabricUsed?: number; // meters of fabric used
  notes?: string;
}

// Order
export interface OrderDB extends BaseDocument {
  memoId?: string;
  customerId: string;
  customerName: string; // Denormalized for quick access
  customerPhone: string; // Denormalized for quick access
  type: 'pickup' | 'delivery';
  status: 'New' | 'In Progress' | 'Ready for Delivery' | 'Delivered' | 'Completed' | 'Cancelled';
  orderDate: Timestamp;
  totalAmount: number;
  paidAmount: number;
  totalArtisanWage: number;
  items: OrderItemDB[];
  deliveryDate?: Timestamp;
  deliveryAddress?: string;
  artisanId?: string;
  artisanName?: string; // Denormalized
  cuttingMasterId?: string;
  cuttingMasterName?: string; // Denormalized
  artisanAssignedDate?: Timestamp;
  artisanCompletedDate?: Timestamp;
  cuttingCompletedDate?: Timestamp;
  shopId: string;
  notes?: string;
  priority: 'low' | 'medium' | 'high';
}

// Income Transaction
export interface IncomeTransactionDB extends BaseDocument {
  category: string;
  amount: number;
  description: string;
  transactionDate: Timestamp;
  shopId: string;
  orderId?: string; // Link to order if income is from order
  paymentMethod: 'cash' | 'card' | 'upi' | 'bank_transfer' | 'other';
  isEditable: boolean;
}

// Expense Transaction
export interface ExpenseTransactionDB extends BaseDocument {
  category: string;
  amount: number;
  description?: string;
  person?: string;
  transactionDate: Timestamp;
  shopId: string;
  employeeId?: string; // If expense is related to employee (salary, advance)
  receiptUrl?: string; // URL to receipt image
  isEditable: boolean;
  paymentMethod: 'cash' | 'card' | 'upi' | 'bank_transfer' | 'other';
}

// Settings
export interface AppearanceSettingsDB extends BaseDocument {
  theme: 'light' | 'dark';
  font: 'inter' | 'manrope' | 'system' | 'poppins' | 'pt-sans';
  shopId: string;
}

export interface NotificationSettingsDB extends BaseDocument {
  smsEnabled: boolean;
  smsProvider: 'twilio' | 'other';
  smsApiKey?: string;
  smsApiSecret?: string;
  smsSenderId?: string;
  smsMessageTemplate?: string;
  whatsappEnabled: boolean;
  whatsappApiKey?: string;
  whatsappSenderNumber?: string;
  whatsappMessageTemplate?: string;
  shopId: string;
}

// Audit Log for tracking changes
export interface AuditLogDB extends BaseDocument {
  action: 'create' | 'update' | 'delete';
  entityType: string;
  entityId: string;
  userId: string;
  userName: string;
  changes?: Record<string, any>;
  shopId: string;
}

// Report Data (for caching complex calculations)
export interface ReportDataDB extends BaseDocument {
  reportType: 'daily' | 'weekly' | 'monthly' | 'yearly';
  startDate: Timestamp;
  endDate: Timestamp;
  totalIncome: number;
  totalExpenses: number;
  netProfit: number;
  orderCount: number;
  customerCount: number;
  shopId: string;
  data: Record<string, any>; // Flexible data structure for different report types
}

// Collection names as constants
export const COLLECTIONS = {
  SHOPS: 'shops',
  USERS: 'users',
  CUSTOMERS: 'customers',
  CUSTOMER_MEASUREMENTS: 'customerMeasurements',
  INVENTORY: 'inventory',
  TAILORING_ITEMS: 'tailoringItems',
  EMPLOYEES: 'employees',
  ORDERS: 'orders',
  INCOME_TRANSACTIONS: 'incomeTransactions',
  EXPENSE_TRANSACTIONS: 'expenseTransactions',
  APPEARANCE_SETTINGS: 'appearanceSettings',
  NOTIFICATION_SETTINGS: 'notificationSettings',
  AUDIT_LOGS: 'auditLogs',
  REPORT_DATA: 'reportData',
} as const;

// Subcollection names
export const SUBCOLLECTIONS = {
  MEASUREMENTS: 'measurements',
  ORDER_ITEMS: 'orderItems',
  TRANSACTIONS: 'transactions',
} as const;

// Query result types
export interface QueryResult<T> {
  data: T[];
  lastDoc?: any;
  hasMore: boolean;
  total?: number;
}

export interface PaginationOptions {
  limit?: number;
  startAfter?: any;
  orderBy?: string;
  orderDirection?: 'asc' | 'desc';
}

export interface FilterOptions {
  field: string;
  operator: '==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any';
  value: any;
}

// Database operation result
export interface DatabaseResult<T = any> {
  success: boolean;
  data?: T;
  error?: string;
  code?: string;
}
