import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { AppDataSource, parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AuthContext } from '@d8d/shared-types';
import { PrinterService } from '../../services/printer.service';
import { getFeieApiConfig } from '../utils/feie-config.util';

// 打印机创建请求Schema
const PrinterCreateRequestSchema = z.object({
  printerSn: z.string().min(1, '打印机SN不能为空'),
  printerKey: z.string().min(1, '打印机密钥不能为空'),
  printerName: z.string().optional(),
  printerType: z.enum(['58mm', '80mm']).default('58mm'),
  isDefault: z.boolean().default(false)
});

// 打印机创建响应Schema
const PrinterCreateResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    id: z.number(),
    tenantId: z.number(),
    printerSn: z.string(),
    printerName: z.string().nullable(),
    printerKey: z.string(),
    printerType: z.enum(['58mm', '80mm']),
    printerStatus: z.enum(['ONLINE', 'OFFLINE', 'ERROR']),
    isDefault: z.number(),
    createdAt: z.string(),
    updatedAt: z.string()
  })
});

// 打印机创建路由定义
const printerCreateRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: PrinterCreateRequestSchema }
      }
    }
  },
  responses: {
    200: {
      description: '打印机添加成功',
      content: { 'application/json': { schema: PrinterCreateResponseSchema } }
    },
    400: {
      description: '参数错误或配置错误',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: z.object({ message: z.string() }) } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(printerCreateRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;

    try {
      const body = c.req.valid('json');

      // 获取飞鹅API配置
      const feieConfig = await getFeieApiConfig(tenantId, AppDataSource);
      if (!feieConfig) {
        return c.json({ success: false, message: '飞鹅API配置未找到或配置不完整' }, 400);
      }

      // 创建带配置的服务实例
      const printerService = new PrinterService(AppDataSource, feieConfig);
      const printer = await printerService.addPrinter(tenantId, body);

      // 验证响应格式
      const response = {
        success: true as const,
        data: printer
      };
      const validatedResponse = await parseWithAwait(PrinterCreateResponseSchema, response);

      return c.json(validatedResponse, 200);
    } catch (error) {
      console.error(`[租户${tenantId}] 添加打印机失败:`, error);
      const errorMessage = error instanceof Error ? error.message : '添加打印机失败';
      return c.json({ success: false, message: errorMessage }, 500);
    }
  });

export default app;