import { Request, Response } from 'express';
import { ConfigService } from '../../services/ConfigService';
import { AuditService } from '../../services/AuditService';

export class ConfigController {
  static async getAll(req: Request, res: Response) {
    try {
      const configs = await ConfigService.getAllConfigs();
      res.json({ success: true, data: configs });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  static async update(req: Request, res: Response) {
    const key = String(req.params.key);
    const { isEnabled, value } = req.body;
    const { tenantId, shopId, taskId, traceId, userId } = (req as any).traceContext;

    try {
      const beforeSnapshot = await ConfigService.getConfig(key);
      if (!beforeSnapshot) return res.status(404).json({ success: false, error: 'Config not found' });

      await ConfigService.updateConfig(key, { isEnabled, value });
      
      const afterSnapshot = await ConfigService.getConfig(key);

      await AuditService.logDiff({
        tenantId,
        shopId,
        taskId,
        traceId,
        userId,
        module: 'CONFIG',
        action: 'UPDATE_CONFIG',
        resourceType: 'config',
        resourceId: key,
        beforeSnapshot,
        afterSnapshot,
        source: 'console'
      });

      res.json({ success: true });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  static async getByKey(req: Request, res: Response) {
    const key = String(req.params.key);
    try {
      const config = await ConfigService.getConfig(key);
      if (!config) return res.status(404).json({ success: false, error: 'Config not found' });
      res.json({ success: true, data: config });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }
}
