import { Request, Response } from 'express';
import { WebhookService } from '../../services/WebhookService';
import { logger } from '../../utils/logger';

/**
 * [BIZ_INT_12] 企业 Webhook 配置控制器
 */
export class WebhookController {
  /**
   * 获取当前租户的 Webhook 配置
   * GET /api/v1/webhook/config
   */
  static async getConfig(req: Request, res: Response) {
    const tenantId = req.headers['x-tenant-id'] as string;

    if (!tenantId) {
      return res.status(400).json({ success: false, error: 'x-tenant-id header is required' });
    }

    try {
      const config = await WebhookService.getConfig(tenantId);
      return res.json({
        success: true,
        data: config || null
      });
    } catch (err: any) {
      logger.error(`[WebhookController] Get config failed: ${err.message}`);
      return res.status(500).json({ success: false, error: 'Internal server error' });
    }
  }

  /**
   * 保存/更新 Webhook 配置
   * POST /api/v1/webhook/config
   */
  static async saveConfig(req: Request, res: Response) {
    const tenantId = req.headers['x-tenant-id'] as string;
    const { url, secret, enabledEvents } = req.body;

    if (!tenantId) {
      return res.status(400).json({ success: false, error: 'x-tenant-id header is required' });
    }

    if (!url || !secret || !Array.isArray(enabledEvents)) {
      return res.status(400).json({ success: false, error: 'url, secret, and enabledEvents[] are required' });
    }

    try {
      await WebhookService.saveConfig(tenantId, {
        url,
        secret,
        enabled_events: enabledEvents
      });

      return res.json({
        success: true,
        message: 'Webhook configuration saved successfully'
      });
    } catch (err: any) {
      logger.error(`[WebhookController] Save config failed: ${err.message}`);
      return res.status(500).json({ success: false, error: 'Internal server error' });
    }
  }
}
