const Config = require('../models/Config');
const CacheUtil = require('../utils/cache');

/**
 * Config Service
 * Handles system configuration operations
 */

const CACHE_PREFIX = 'config:';
const CACHE_TTL = 3600; // 1 hour

/**
 * Get configuration by key
 */
const getConfig = async (key) => {
  // Try cache first
  const cacheKey = CACHE_PREFIX + key;
  const cached = await CacheUtil.get(cacheKey);
  if (cached) {
    return cached;
  }

  // Get from database
  const config = await Config.findOne({ where: { key } });
  
  if (config) {
    // Parse value based on type
    let value = config.value;
    if (config.type === 'json' && value) {
      try {
        value = JSON.parse(value);
      } catch (e) {
        console.error('Failed to parse JSON config:', key, e);
      }
    } else if (config.type === 'number') {
      value = parseFloat(value);
    } else if (config.type === 'boolean') {
      value = value === 'true' || value === '1';
    }

    const result = { ...config.toJSON(), value };
    
    // Cache the result
    await CacheUtil.set(cacheKey, result, CACHE_TTL);
    
    return result;
  }

  return null;
};

/**
 * Get all configurations
 */
const getAllConfigs = async (category = null) => {
  const where = category ? { category } : {};
  const configs = await Config.findAll({ where, order: [['category', 'ASC'], ['key', 'ASC']] });
  
  return configs.map(config => {
    let value = config.value;
    if (config.type === 'json' && value) {
      try {
        value = JSON.parse(value);
      } catch (e) {
        console.error('Failed to parse JSON config:', config.key, e);
      }
    } else if (config.type === 'number') {
      value = parseFloat(value);
    } else if (config.type === 'boolean') {
      value = value === 'true' || value === '1';
    }
    return { ...config.toJSON(), value };
  });
};

/**
 * Set configuration
 */
const setConfig = async (key, value, type = 'string', category = 'general', description = null) => {
  // Convert value to string for storage
  let stringValue = value;
  if (type === 'json') {
    stringValue = JSON.stringify(value);
  } else if (type === 'boolean') {
    stringValue = value ? 'true' : 'false';
  } else if (type === 'number') {
    stringValue = String(value);
  }

  // Upsert configuration
  const [config] = await Config.upsert({
    key,
    value: stringValue,
    type,
    category,
    description,
  });

  // Clear cache
  await CacheUtil.delete(CACHE_PREFIX + key);

  return config;
};

/**
 * Delete configuration
 */
const deleteConfig = async (key) => {
  const result = await Config.destroy({ where: { key } });
  
  // Clear cache
  await CacheUtil.delete(CACHE_PREFIX + key);
  
  return result > 0;
};

/**
 * Get public configurations (for frontend)
 */
const getPublicConfigs = async () => {
  const configs = await getAllConfigs();
  
  // Filter only public configurations
  const publicKeys = ['app_logo', 'about_us_image', 'app_name', 'contact_phone', 'contact_email', 'contact_qr_image', 'user_agreement', 'privacy_policy', 'invite_rules', 'default_avatar'];
  
  const publicConfigs = {};
  configs.forEach(config => {
    if (publicKeys.includes(config.key)) {
      publicConfigs[config.key] = config.value;
    }
  });
  
  return publicConfigs;
};

/**
 * Initialize default configurations
 */
const initializeDefaults = async () => {
  const defaults = [
    { key: 'app_logo', value: '', type: 'image', category: 'appearance', description: 'Application logo image URL' },
    { key: 'about_us_image', value: '', type: 'image', category: 'appearance', description: 'About us section image URL' },
    { key: 'default_avatar', value: '', type: 'image', category: 'appearance', description: '用户默认头像' },
    { key: 'app_name', value: 'Overseas Appointment System', type: 'string', category: 'general', description: 'Application name' },
    { key: 'contact_phone', value: '', type: 'string', category: 'contact', description: 'Contact phone number' },
    { key: 'contact_email', value: '', type: 'string', category: 'contact', description: 'Contact email address' },
    { key: 'contact_qr_image', value: '', type: 'image', category: 'contact', description: 'Contact us QR code image URL' },
    { key: 'user_agreement', value: '', type: 'text', category: 'agreement', description: 'User agreement content' },
    { key: 'privacy_policy', value: '', type: 'text', category: 'agreement', description: 'Privacy policy content' },
    { key: 'invite_rules', value: '1. 邀请新用户注册并完成首次消费\n2. 每成功邀请一位用户可获得现金奖励\n3. 奖励将在用户完成支付后24小时内到账\n4. 提现金额满100元即可申请提现', type: 'string', category: 'invite', description: '邀请奖励规则说明' },
  ];

  for (const config of defaults) {
    const existing = await Config.findOne({ where: { key: config.key } });
    if (!existing) {
      await Config.create(config);
    }
  }
};

module.exports = {
  getConfig,
  getAllConfigs,
  setConfig,
  deleteConfig,
  getPublicConfigs,
  initializeDefaults,
};
