/**
 * Configuration Service
 * Fetches and caches system configuration from backend
 */

import apiClient from './authApi';

export interface SystemConfig {
  appName: string;
  appVersion: string;
  workingHours: {
    START_HOUR: number;
    END_HOUR: number;
    START_DAY: number;
    END_DAY: number;
    TIMEZONE: string;
  };
  tat: {
    thresholds: {
      warning: number;
      critical: number;
      breach: number;
    };
    testMode: boolean;
  };
  upload: {
    maxFileSizeMB: number;
    allowedFileTypes: string[];
    maxFilesPerRequest: number;
  };
  workflow: {
    maxApprovalLevels: number;
    maxParticipants: number;
    maxSpectators: number;
  };
  workNotes: {
    maxMessageLength: number;
    maxAttachmentsPerNote: number;
    enableReactions: boolean;
    enableMentions: boolean;
  };
  features: {
    ENABLE_AI_CONCLUSION: boolean;
    ENABLE_TEMPLATES: boolean;
    ENABLE_ANALYTICS: boolean;
    ENABLE_EXPORT: boolean;
  };
  ui: {
    DEFAULT_THEME: string;
    DEFAULT_LANGUAGE: string;
    DATE_FORMAT: string;
    TIME_FORMAT: string;
    CURRENCY: string;
    CURRENCY_SYMBOL: string;
  };
}

// Default fallback configuration
const DEFAULT_CONFIG: SystemConfig = {
  appName: 'Royal Enfield Workflow Management',
  appVersion: '1.2.0',
  workingHours: {
    START_HOUR: 9,
    END_HOUR: 18,
    START_DAY: 1,
    END_DAY: 5,
    TIMEZONE: 'Asia/Kolkata',
  },
  tat: {
    thresholds: {
      warning: 50,
      critical: 75,
      breach: 100,
    },
    testMode: false,
  },
  upload: {
    maxFileSizeMB: 10,
    allowedFileTypes: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'jpg', 'jpeg', 'png', 'gif'],
    maxFilesPerRequest: 10,
  },
  workflow: {
    maxApprovalLevels: 10,
    maxParticipants: 50,
    maxSpectators: 20,
  },
  workNotes: {
    maxMessageLength: 2000,
    maxAttachmentsPerNote: 5,
    enableReactions: true,
    enableMentions: true,
  },
  features: {
    ENABLE_AI_CONCLUSION: true,
    ENABLE_TEMPLATES: false,
    ENABLE_ANALYTICS: true,
    ENABLE_EXPORT: true,
  },
  ui: {
    DEFAULT_THEME: 'light',
    DEFAULT_LANGUAGE: 'en',
    DATE_FORMAT: 'DD/MM/YYYY',
    TIME_FORMAT: '12h',
    CURRENCY: 'INR',
    CURRENCY_SYMBOL: '₹',
  },
};

class ConfigService {
  private config: SystemConfig | null = null;
  private loading: Promise<SystemConfig> | null = null;

  /**
   * Get system configuration (cached)
   * Automatically fetches from backend on first call
   */
  async getConfig(): Promise<SystemConfig> {
    // Return cached config if available
    if (this.config) {
      return this.config;
    }

    // If already loading, wait for that request
    if (this.loading) {
      return this.loading;
    }

    // Fetch from backend
    this.loading = this.fetchConfig();
    this.config = await this.loading;
    this.loading = null;

    return this.config;
  }

  /**
   * Fetch configuration from backend
   */
  private async fetchConfig(): Promise<SystemConfig> {
    try {
      const response = await apiClient.get('/config');
      const serverConfig = response.data?.data || response.data;
      
      // Merge with defaults (in case server doesn't return all fields)
      return {
        ...DEFAULT_CONFIG,
        ...serverConfig,
        workingHours: { ...DEFAULT_CONFIG.workingHours, ...serverConfig.workingHours },
        tat: { ...DEFAULT_CONFIG.tat, ...serverConfig.tat },
        upload: { ...DEFAULT_CONFIG.upload, ...serverConfig.upload },
        workflow: { ...DEFAULT_CONFIG.workflow, ...serverConfig.workflow },
        workNotes: { ...DEFAULT_CONFIG.workNotes, ...serverConfig.workNotes },
        features: { ...DEFAULT_CONFIG.features, ...serverConfig.features },
        ui: { ...DEFAULT_CONFIG.ui, ...serverConfig.ui },
      };
    } catch (error) {
      console.error('[ConfigService] ⚠️ Failed to fetch config from server, using defaults:', error);
      return DEFAULT_CONFIG;
    }
  }

  /**
   * Force refresh configuration from backend
   */
  async refreshConfig(): Promise<SystemConfig> {
    this.config = null;
    this.loading = null;
    return this.getConfig();
  }

  /**
   * Get cached config synchronously (returns null if not loaded)
   */
  getCachedConfig(): SystemConfig | null {
    return this.config;
  }

  /**
   * Check if config is loaded
   */
  isLoaded(): boolean {
    return this.config !== null;
  }
}

// Export singleton instance
export const configService = new ConfigService();

// Export helper functions for common config values
export async function getWorkingHours() {
  const config = await configService.getConfig();
  return config.workingHours;
}

export async function getTATThresholds() {
  const config = await configService.getConfig();
  return config.tat.thresholds;
}

export async function getUploadLimits() {
  const config = await configService.getConfig();
  return config.upload;
}

export async function getWorkflowLimits() {
  const config = await configService.getConfig();
  return config.workflow;
}

export async function getWorkNotesConfig() {
  const config = await configService.getConfig();
  return config.workNotes;
}

export async function getFeatureFlags() {
  const config = await configService.getConfig();
  return config.features;
}

