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 PrinterListQuerySchema = z.object({
  page: z.string().optional().transform(val => val ? parseInt(val, 10) : 1),
  pageSize: z.string().optional().transform(val => val ? parseInt(val, 10) : 10),
  search: z.string().optional(),
  status: z.enum(['ACTIVE', 'INACTIVE', 'ERROR', 'ALL']).optional().default('ALL'),
  printerType: z.enum(['58mm', '80mm', 'ALL']).optional().default('ALL'),
  isDefault: z.enum(['true', 'false']).optional().transform(val => val === 'true')
});

// 打印机列表响应Schema
const PrinterListResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    data: z.array(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()
    })),
    total: z.number(),
    page: z.number(),
    pageSize: z.number()
  })
});

// 打印机列表路由定义
const printerListRoute = createRoute({
  method: 'get',
  path: '/',
  middleware: [authMiddleware],
  request: {
    query: PrinterListQuerySchema
  },
  responses: {
    200: {
      description: '打印机列表获取成功',
      content: { 'application/json': { schema: PrinterListResponseSchema } }
    },
    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(printerListRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;

    // 获取查询参数
    const query = c.req.valid('query');
    const { page, pageSize, search, status, printerType, isDefault } = query;

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

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

    // 应用筛选逻辑
    let filteredPrinters = printers;

    // 搜索筛选
    if (search) {
      filteredPrinters = filteredPrinters.filter(p =>
        (p.printerName && p.printerName.includes(search)) ||
        p.printerSn.includes(search)
      );
    }

    // 状态筛选
    if (status && status !== 'ALL') {
      filteredPrinters = filteredPrinters.filter(p => p.printerStatus === status);
    }

    // 类型筛选
    if (printerType && printerType !== 'ALL') {
      filteredPrinters = filteredPrinters.filter(p => p.printerType === printerType);
    }

    // 默认打印机筛选
    if (isDefault) {
      filteredPrinters = filteredPrinters.filter(p => p.isDefault === 1);
    }

    // 分页逻辑
    const total = filteredPrinters.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, total);
    const paginatedPrinters = filteredPrinters.slice(startIndex, endIndex);

    console.debug(`返回打印机列表，总数: ${total}, 分页: ${page}/${Math.ceil(total/pageSize)}, 数量: ${paginatedPrinters.length}`);

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

    // 验证响应格式
    const validatedResponse = await parseWithAwait(PrinterListResponseSchema, {
      success: true,
      data: {
        data: transformedPrinters,
        total,
        page,
        pageSize
      }
    });

    return c.json(validatedResponse, 200);
  });

export default app;