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 PrinterUpdateRequestSchema = z.object({
  printerName: z.string().optional(),
  printerKey: z.string().optional(),
  printerType: z.enum(['58mm', '80mm']).optional(),
  isDefault: z.boolean().optional()
});

// 打印机更新路由参数Schema
const PrinterUpdateParamsSchema = z.object({
  printerSn: z.string()
});

// 打印机更新响应Schema
const PrinterUpdateResponseSchema = 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(['ACTIVE', 'INACTIVE', 'ERROR']),
    isDefault: z.number(),
    createdAt: z.string(),
    updatedAt: z.string()
  })
});

// 打印机更新路由定义
const printerUpdateRoute = createRoute({
  method: 'put',
  path: '/:printerSn',
  middleware: [authMiddleware],
  request: {
    params: PrinterUpdateParamsSchema,
    body: {
      content: {
        'application/json': { schema: PrinterUpdateRequestSchema }
      }
    }
  },
  responses: {
    200: {
      description: '打印机更新成功',
      content: { 'application/json': { schema: PrinterUpdateResponseSchema } }
    },
    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() }) } }
    },
    404: {
      description: '打印机不存在',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(printerUpdateRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;
    const { printerSn } = c.req.valid('param');

    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.updatePrinter(tenantId, printerSn, body);

      // 转换Date对象为ISO字符串
      const transformedPrinter = {
        ...printer,
        createdAt: printer.createdAt.toISOString(),
        updatedAt: printer.updatedAt.toISOString()
      };

      // 验证响应格式
      const validatedResponse = await parseWithAwait(PrinterUpdateResponseSchema, {
        success: true,
        data: transformedPrinter
      });

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

export default app;