
// Enums
export enum UserRole {
  ADMIN = 'System Administrator',
  ASSET_OWNER = 'Asset Owner',
  OM_MANAGER = 'O&M Manager',
  TECHNICIAN = 'Technician',
  HSE_OFFICER = 'HSE Officer'
}

export enum AssetStatus {
  OPERATIONAL = 'active',
  MAINTENANCE = 'maintenance',
  INACTIVE = 'inactive',
  DECOMMISSIONED = 'decommissioned',
  FAULTY = 'faulty' // Kept for UI compatibility though not in strict schema
}

export enum TicketStatus {
  OPEN = 'Open',
  ASSIGNED = 'Assigned',
  IN_PROGRESS = 'InProgress',
  RESOLVED = 'Resolved',
  CLOSED = 'Closed',
  PENDING_PARTS = 'PendingParts' // UI specific
}

export enum TicketType {
  CM = 'CM',
  PM = 'PM',
  CLEANING = 'Cleaning',
  INSPECTION = 'Inspection',
  PREDICTIVE = 'Predictive' // UI specific
}

// --- 1. Asset Management ---

export interface ICompany {
  _id: string;
  name: string;
  code: string;
  taxCode?: string;
  address?: string;
  phone?: string;
  email?: string;
  status: 'active' | 'inactive';
}

export interface IProject {
  _id: string;
  companyId: string;
  segment?: 'residential' | 'commercial';
  name: string;
  code: string;
  location: {
    address: string;
    coordinates: { lat: number, lng: number };
  };
  capacityMWp: number;
  commissioningDate: string;
  status: 'planning' | 'construction' | 'operational' | 'decommissioned';
  managerId?: string; // UI Helper
  meteocontrol?: {
    siteKey?: string;
    apiKey?: string;
    systemKey?: string;
    useV2API?: boolean;
  };
}

export interface IAsset {
  _id: string;
  projectId: string;
  parentAssetId?: string | null;
  assetType: string;
  name: string;
  code: string;
  serialNumber?: string;
  manufacturer?: string;
  model?: string;
  capacityKW?: number;
  commissioningDate?: string;
  warrantyEndDate?: string;
  status: AssetStatus;
  locationGPS?: { lat: number, lng: number };
  specifications?: Record<string, any>;
  installDate?: string; // Legacy support
}

// --- 2. Contract Management (Expanded) ---

export type CustomerGroup = string; // Now dynamic from MongoDB

export interface ICustomerGroup {
  _id: string;
  name: string;
  code: string;
  description?: string;
  isActive: boolean;
  createdAt?: string;
  updatedAt?: string;
}

export interface IContractType {
  _id: string;
  name: string;
  code: string;
  description?: string;
  isActive: boolean;
  createdAt?: string;
  updatedAt?: string;
}
export type ContractStatus = 'active' | 'draft' | 'expired' | 'terminated' | 'negotiating' | 'suspended' | 'completed' | 'Expiring'; // Expiring for UI

export interface IRevenueDistribution {
  year: number;
  q1: number;
  q2: number;
  q3: number;
  q4: number;
}

export interface IContract {
  _id: string;
  projectId: string;
  contractType: string; // Now dynamic from MongoDB ContractType collection
  contractNumber: string;

  // Parties
  partyA: string; // Customer
  partyB: string; // Service Provider

  // Customer Info (New 3.0.1)
  customerCode?: string;
  customerGroup?: CustomerGroup;
  siteAddress?: string;
  capacityKWp?: number; // Project Capacity in Contract

  // Dates
  startDate: string;
  endDate: string;

  // Financials (New 3.0.4)
  value?: number;
  currency?: string;
  isFree?: boolean; // Classification: Paid vs Free (EPC)
  paymentCycle?: '30_days' | '60_days' | 'custom';
  revenuePlan?: IRevenueDistribution[]; // Quarterly distribution
  debtAmount?: number; // Overdue debt

  // Service Tracking (New 3.0.2)
  serviceTotal?: number; // Total services committed
  servicePerformed?: number; // Services done
  serviceFrequency?: string; // e.g. "4 times/year"

  // Lifecycle (New 3.0.5)
  status: ContractStatus;
  notes?: string; // Reason/Notes
  documentUrl?: string;
}

// --- 3. O&M ---

export interface ITicket {
  _id: string;
  projectId: string;
  assetId: string;
  contractId?: string; // Link to specific O&M Contract
  code: string; // Helper
  ticketType: TicketType;
  title: string;
  description?: string;
  priority: 'Low' | 'Medium' | 'High' | 'Critical';
  status: TicketStatus;
  reportedBy: string; // User ID
  assignedTo?: string; // User ID
  createdAt: string;
  slaDeadline: string; // Helper
  resolvedAt?: string;
  closedAt?: string;
  createdBy?: string; // Legacy alias for reportedBy
}

export interface IWorkOrder {
  _id: string;
  woCode: string; // Helper
  ticketId?: string;
  projectId: string;
  assetId: string;
  contractId?: string; // Link to specific O&M Contract
  workOrderType: 'PM' | 'CM' | 'Cleaning' | 'Inspection' | 'Upgrade';
  title: string;
  description?: string;
  status: 'Draft' | 'Approved' | 'InProgress' | 'Completed' | 'Cancelled' | 'In Progress' | 'Verified'; // UI Mappings
  priority: 'Low' | 'Medium' | 'High'; // UI Helper
  scheduledStart?: string;
  scheduledEnd?: string;
  actualStart?: string;
  actualEnd?: string;
  assignedTechnicianId?: string;
  supervisorId?: string;
  costLabor: number;
  costMaterial: number;
  costExternal: number;
  totalCost: number;
  checklistProgress?: number; // UI Helper
  assignedTo?: string; // Legacy alias
  type?: string; // Legacy alias
  scheduledDate?: string; // Legacy alias
}

export interface IPMSchedule {
  _id: string;
  contractId: string; // Required: Link to O&M Contract
  assetId?: string; // Optional: Reference to customer asset (for information only)
  projectId: string;
  title: string;
  description?: string;
  frequency: 'Daily' | 'Weekly' | 'Monthly' | 'Quarterly' | 'Semi-Annually' | 'Annually';
  lastPerformed?: string;
  nextDue: string;
  assignedTo?: string;
  status: 'Active' | 'Paused' | 'Inactive';

  // Legacy/Helper
  taskName?: string;
  pmType?: string;
  frequencyMonths?: number;
  lastPerformedDate?: string;
  nextDueDate?: string;
  assignedRole?: string;
}

// --- 4. Inventory ---

export interface IInventoryItem {
  _id: string;
  itemCode: string;
  name: string;
  category: 'CriticalSpare' | 'Consumable' | 'Tool' | 'Equipment' | 'Critical Spare' | 'Safety Gear'; // Mapped
  unit: string;
  minStockLevel: number;
  maxStockLevel?: number;
  reorderPoint?: number;
  currentStock: number;
  unitCost?: number;
  supplierId?: string;
  location?: string;
  minStock?: number; // Legacy alias
  quantity?: number; // Legacy alias for currentStock
  supplier?: string; // Legacy string vs ID
}

export interface IInventoryTransaction {
  _id: string;
  itemId: string | IInventoryItem;
  type: 'In' | 'Out';
  quantity: number;
  unitCost?: number;
  notes?: string;
  performedBy?: string;
  timestamp: string;
}

export interface ISupplier {
  _id: string;
  name: string;
  code?: string;
  contactPerson?: string;
  phone?: string;
  email?: string;
  status: 'active' | 'inactive';
}

// --- 5. Financial ---

export interface IBudget {
  _id: string;
  projectId: string;
  budgetYear: number;
  budgetType: 'OPEX' | 'CAPEX';
  category: string;
  plannedAmount: number;
  actualAmount: number;
  variance: number;
}

export interface IFinancialData {
  month: string;
  revenue: number;
  opex: number;
  netProfit: number;
  cumulativeROI: number;
}

export interface ICostBreakdown {
  name: string;
  value: number;
}

// --- 6. User & System ---

export interface IUser {
  _id: string;
  email: string;
  name: string; // Helper combining firstName + lastName
  firstName?: string;
  lastName?: string;
  role: string; // Role name from MongoDB (e.g., "System Administrator", "Technician")
  /** Mã vai trò (ADMIN, OM_MANAGER, …) — gắn từ API /auth/me, login */
  roleCode?: string;
  /** Quyền hiệu lực theo vai trò — gắn từ API */
  rolePermissions?: Record<string, boolean>;
  department?: string;
  status: 'Active' | 'Suspended' | 'Disabled';
  active?: boolean; // Legacy alias
  companyId?: string;
  scope: string[]; // Helper for Project Access
  avatar?: string;
}

export interface IRole {
  _id: string;
  name: string;
  code: string;
  description?: string;
  permissions: Record<string, boolean>;
  isSystem: boolean;
  isActive: boolean;
  createdAt?: string;
  updatedAt?: string;
}

export interface IAuditLog {
  _id: string;
  userId: string;
  action: 'CREATE' | 'UPDATE' | 'DELETE' | 'LOGIN' | 'APPROVE' | 'SYSTEM_CONFIG' | 'EXPORT';
  targetCollection: string; // resourceType
  targetId?: string; // resourceId
  timestamp: string; // createdAt
  details: string; // derived from changes
}

export interface ISystemSettings {
  systemName: string;
  logoUrl: string;
  maintenanceMode: boolean;
  smtp: {
    host: string;
    port: number;
    user: string;
    pass: string;
    secure: boolean;
    senderEmail: string;
  };
  retentionPolicy: {
    logDays: number;
    reportDays: number;
  };
  vcomApi?: {
    username: string;
    password: string;
    apiKey: string;
  };
}

export interface IAlert {
  _id: string;
  type: 'LowStock' | 'PMSchedule' | 'TicketSLA' | 'System';
  message: string;
  severity: 'Info' | 'Warning' | 'Critical';
  createdAt: string;
  isRead: boolean;
  link?: string; // Link to resource
}

// --- 7. Others ---

export interface IKPI {
  _id: string;
  siteId: string; // Legacy mapped to ProjectId
  date: string;
  pr: number;
  availability: number;
  specificYield: number;
  irradiation: number;
  production: number;
}

export interface IReport {
  _id: string;
  title: string;
  type: 'Daily' | 'Monthly' | 'Audit' | 'Financial' | 'Custom';
  generatedDate: string;
  /** Chuỗi ID/email hoặc object người tạo từ API */
  createdBy: string | { name?: string; email?: string };
  format: 'PDF' | 'Excel' | 'Word';
  size: string;
  status: 'Ready' | 'Processing' | 'Failed';
  downloadUrl?: string;
}

// Compliance / Risk (Extended from Docs)
export interface IComplianceDoc {
  _id: string;
  siteId: string; // Mapped to ProjectId
  name: string;
  type: string;
  issueDate: string;
  expiryDate: string;
  status: 'Valid' | 'Expiring Soon' | 'Expired';
  issuingAuthority: string;
  documentUrl?: string;
}

export interface IHSEIncident {
  _id: string;
  siteId: string;
  date: string;
  type: string;
  description: string;
  severity: string;
  status: string;
  mitigationAction: string;
}

export interface IRiskAssessment {
  _id: string;
  riskCategory: string;
  description: string;
  probability: string;
  impact: string;
  riskLevel: string;
  mitigationStrategy: string;
}

// Activity Helper
export interface ITicketActivity {
  _id: string;
  ticketId: string;
  action: string;
  performedBy: string;
  timestamp: string;
  details?: string;
  statusBefore?: TicketStatus;
  statusAfter?: TicketStatus;
}
