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 PrinterDeleteParamsSchema = z.object({
  printerSn: z.string()
});

// 打印机删除响应Schema
const PrinterDeleteResponseSchema = z.object({
  success: z.boolean(),
  message: z.string()
});

// 打印机删除路由定义
const printerDeleteRoute = createRoute({
  method: 'delete',
  path: '/:printerSn',
  middleware: [authMiddleware],
  request: {
    params: PrinterDeleteParamsSchema
  },
  responses: {
    200: {
      description: '打印机删除成功',
      content: { 'application/json': { schema: PrinterDeleteResponseSchema } }
    },
    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(printerDeleteRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;
    const { printerSn } = c.req.valid('param');

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

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

      // 验证响应格式
      const validatedResponse = await parseWithAwait(PrinterDeleteResponseSchema, {
        success: true,
        message: '打印机删除成功'
      });

      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;