import { OpenAPIHono } from '@hono/zod-openapi';
import { DataSource } from 'typeorm';
import { PrinterService } from '../services/printer.service';
import { PrintTaskService } from '../services/print-task.service';
import { DelaySchedulerService } from '../services/delay-scheduler.service';
import { FeieApiConfig } from '../types/feie.types';

// 飞鹅API配置（应该从环境变量或配置服务获取）
const DEFAULT_FEIE_CONFIG: FeieApiConfig = {
  baseUrl: process.env.FEIE_API_BASE_URL || 'http://api.feieyun.cn/Api/Open/',
  user: process.env.FEIE_API_USER || '',
  ukey: process.env.FEIE_API_UKEY || '',
  timeout: parseInt(process.env.FEIE_API_TIMEOUT || '10000'),
  maxRetries: parseInt(process.env.FEIE_API_MAX_RETRIES || '3')
};

export function createFeieRoutes(dataSource: DataSource) {
  const app = new OpenAPIHono();

  // 初始化服务
  const printerService = new PrinterService(dataSource, DEFAULT_FEIE_CONFIG);
  const printTaskService = new PrintTaskService(dataSource, DEFAULT_FEIE_CONFIG);
  const delaySchedulerService = new DelaySchedulerService(dataSource, DEFAULT_FEIE_CONFIG);

  // 打印机管理路由
  app.get('/printers', async (c) => {
    const tenantId = 1; // 从认证中间件获取
    const printers = await printerService.getPrinters(tenantId);
    return c.json({ success: true, data: printers });
  });

  app.post('/printers', async (c) => {
    const tenantId = 1;
    const body = await c.req.json();
    const printer = await printerService.addPrinter(tenantId, body);
    return c.json({ success: true, data: printer });
  });

  app.get('/printers/:printerSn', async (c) => {
    const tenantId = 1;
    const printerSn = c.req.param('printerSn');
    const printer = await (printerService as any).findOne({
      where: { tenantId, printerSn }
    });

    if (!printer) {
      return c.json({ success: false, message: '打印机不存在' }, 404);
    }

    return c.json({ success: true, data: printer });
  });

  app.put('/printers/:printerSn', async (c) => {
    const tenantId = 1;
    const printerSn = c.req.param('printerSn');
    const body = await c.req.json();
    const printer = await printerService.updatePrinter(tenantId, printerSn, body);
    return c.json({ success: true, data: printer });
  });

  app.delete('/printers/:printerSn', async (c) => {
    const tenantId = 1;
    const printerSn = c.req.param('printerSn');
    await printerService.deletePrinter(tenantId, printerSn);
    return c.json({ success: true, message: '打印机删除成功' });
  });

  app.get('/printers/:printerSn/status', async (c) => {
    const tenantId = 1;
    const printerSn = c.req.param('printerSn');
    const status = await printerService.getPrinterStatus(tenantId, printerSn);
    return c.json({ success: true, data: status });
  });

  app.post('/printers/:printerSn/set-default', async (c) => {
    const tenantId = 1;
    const printerSn = c.req.param('printerSn');
    const printer = await printerService.setDefaultPrinter(tenantId, printerSn);
    return c.json({ success: true, data: printer });
  });

  // 打印任务管理路由
  app.post('/tasks', async (c) => {
    const tenantId = 1;
    const body = await c.req.json();
    const task = await printTaskService.createPrintTask(tenantId, body);
    return c.json({ success: true, data: task });
  });

  app.get('/tasks', async (c) => {
    const tenantId = 1;
    const query = c.req.query();
    const filters = {
      orderId: query.orderId ? parseInt(query.orderId, 10) : undefined,
      printerSn: query.printerSn,
      printType: query.printType as any,
      printStatus: query.printStatus as any,
      startDate: query.startDate ? new Date(query.startDate) : undefined,
      endDate: query.endDate ? new Date(query.endDate) : undefined
    };
    const page = query.page ? parseInt(query.page, 10) : 1;
    const limit = query.limit ? parseInt(query.limit, 10) : 20;

    const result = await printTaskService.getPrintTasks(tenantId, filters, page, limit);
    return c.json({ success: true, data: result.tasks, total: result.total, page, limit });
  });

  app.get('/tasks/:taskId', async (c) => {
    const tenantId = 1;
    const taskId = c.req.param('taskId');
    const task = await (printTaskService as any).findOne({
      where: { tenantId, taskId }
    });

    if (!task) {
      return c.json({ success: false, message: '打印任务不存在' }, 404);
    }

    return c.json({ success: true, data: task });
  });

  app.get('/tasks/:taskId/status', async (c) => {
    const tenantId = 1;
    const taskId = c.req.param('taskId');
    const status = await printTaskService.getPrintTaskStatus(tenantId, taskId);
    return c.json({ success: true, data: status });
  });

  app.post('/tasks/:taskId/cancel', async (c) => {
    const tenantId = 1;
    const taskId = c.req.param('taskId');
    const body = await c.req.json();
    const task = await printTaskService.cancelPrintTask(tenantId, taskId, body.reason);
    return c.json({ success: true, data: task });
  });

  app.post('/tasks/:taskId/retry', async (c) => {
    const tenantId = 1;
    const taskId = c.req.param('taskId');
    const task = await printTaskService.retryPrintTask(tenantId, taskId);
    return c.json({ success: true, data: task });
  });

  // 调度器管理路由
  app.get('/scheduler/status', async (c) => {
    const status = delaySchedulerService.getStatus();
    return c.json({ success: true, data: status });
  });

  app.post('/scheduler/start', async (c) => {
    await delaySchedulerService.start();
    return c.json({ success: true, message: '调度器已启动' });
  });

  app.post('/scheduler/stop', async (c) => {
    await delaySchedulerService.stop();
    return c.json({ success: true, message: '调度器已停止' });
  });

  app.get('/scheduler/health', async (c) => {
    const health = await delaySchedulerService.healthCheck();
    return c.json({ success: true, data: health });
  });

  return app;
}

export default createFeieRoutes;