import { Request, Response } from 'express';
import { OrderCentralService, OrderCentralContext, Platform } from '../../services/order/OrderCentralService';

export class OrderCentralController {
  static async initTables(req: Request, res: Response): Promise<void> {
    try {
      await OrderCentralService.initTables();
      res.json({ success: true, message: 'Order central tables initialized' });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  static async registerPlatform(req: Request, res: Response): Promise<void> {
    try {
      const context = OrderCentralController.getContext(req);
      const { platform, shopId, shopName, credentials, syncEnabled, syncInterval } = req.body;

      const result = await OrderCentralService.registerPlatform(context, {
        platform,
        shopId,
        shopName,
        credentials,
        syncEnabled: syncEnabled ?? true,
        syncInterval: syncInterval ?? 30
      });

      res.status(201).json(result);
    } catch (error: any) {
      res.status(400).json({ success: false, error: error.message });
    }
  }

  static async collectOrders(req: Request, res: Response): Promise<void> {
    try {
      const context = OrderCentralController.getContext(req);
      const { platform, shopId, startDate, endDate } = req.body;

      const result = await OrderCentralService.collectOrders(context, {
        platform,
        shopId,
        startDate: startDate ? new Date(startDate) : undefined,
        endDate: endDate ? new Date(endDate) : undefined
      });

      res.status(201).json(result);
    } catch (error: any) {
      res.status(400).json({ success: false, error: error.message });
    }
  }

  static async getOrders(req: Request, res: Response): Promise<void> {
    try {
      const context = OrderCentralController.getContext(req);
      const { platforms, shopIds, funnelStage, status, startDate, endDate, search, page, pageSize } = req.query;

      const result = await OrderCentralService.getCentralizedOrders(context.tenantId, {
        platforms: platforms ? (platforms as string).split(',') as Platform[] : undefined,
        shopIds: shopIds ? (shopIds as string).split(',') : undefined,
        funnelStage: funnelStage as any,
        status: status as string,
        startDate: startDate ? new Date(startDate as string) : undefined,
        endDate: endDate ? new Date(endDate as string) : undefined,
        search: search as string,
        page: page ? parseInt(page as string) : 1,
        pageSize: pageSize ? parseInt(pageSize as string) : 20
      });

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

  static async getFunnelAnalysis(req: Request, res: Response): Promise<void> {
    try {
      const context = OrderCentralController.getContext(req);
      const { platforms, startDate, endDate } = req.query;

      const result = await OrderCentralService.getFunnelAnalysis(context.tenantId, {
        platforms: platforms ? (platforms as string).split(',') as Platform[] : undefined,
        startDate: startDate ? new Date(startDate as string) : undefined,
        endDate: endDate ? new Date(endDate as string) : undefined
      });

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

  static async getPlatformStats(req: Request, res: Response): Promise<void> {
    try {
      const context = OrderCentralController.getContext(req);
      const { platforms, startDate, endDate } = req.query;

      const result = await OrderCentralService.getPlatformStats(context.tenantId, {
        platforms: platforms ? (platforms as string).split(',') as Platform[] : undefined,
        startDate: startDate ? new Date(startDate as string) : undefined,
        endDate: endDate ? new Date(endDate as string) : undefined
      });

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

  static async getCollectionHistory(req: Request, res: Response): Promise<void> {
    try {
      const context = OrderCentralController.getContext(req);
      const { platform, status, page, pageSize } = req.query;

      const result = await OrderCentralService.getCollectionHistory(context.tenantId, {
        platform: platform as Platform,
        status: status as any,
        page: page ? parseInt(page as string) : 1,
        pageSize: pageSize ? parseInt(pageSize as string) : 20
      });

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

  private static getContext(req: Request): OrderCentralContext {
    return {
      tenantId: req.headers['x-tenant-id'] as string || 'default',
      shopId: req.headers['x-shop-id'] as string || 'default',
      taskId: req.headers['x-task-id'] as string || `task-${Date.now()}`,
      traceId: req.headers['x-trace-id'] as string || `trace-${Date.now()}`,
      businessType: (req.headers['x-business-type'] as 'TOC' | 'TOB') || 'TOC'
    };
  }
}
