import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { GoodsSchema } from '../schemas/goods.schema.mt';
import { ErrorSchema } from '@d8d/shared-utils';
import { AppDataSource } from '@d8d/shared-utils';
import { GoodsMt } from '../entities/goods.entity.mt';
import { AuthContext } from '@d8d/shared-types';
import { parseWithAwait } from '@d8d/shared-utils';

// 定义获取子商品列表路由
console.debug('创建publicGoodsChildrenRoutesMt路由定义');
const routeDef = createRoute({
  method: 'get',
  path: '/{id}/children',
  middleware: [],
  request: {
    params: z.object({
      id: z.coerce.number<number>().int().positive('商品ID必须是正整数').openapi({
        example: 1,
        description: '父商品ID'
      })
    }),
    query: z.object({
      page: z.coerce.number<number>().int().positive('页码必须是正整数').default(1).openapi({
        example: 1,
        description: '页码，从1开始'
      }),
      pageSize: z.coerce.number<number>().int().positive('每页数量必须是正整数').default(10).openapi({
        example: 10,
        description: '每页数量'
      }),
      keyword: z.string().optional().openapi({
        example: '搜索关键词',
        description: '搜索关键词'
      }),
      sortBy: z.string().optional().openapi({
        example: 'createdAt',
        description: '排序字段'
      }),
      sortOrder: z.enum(['ASC', 'DESC']).optional().default('DESC').openapi({
        example: 'DESC',
        description: '排序方向：ASC（升序）或 DESC（降序）'
      })
    })
  },
  responses: {
    200: {
      description: '成功获取子商品列表',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(GoodsSchema),
            total: z.number().int().nonnegative(),
            page: z.number().int().positive(),
            pageSize: z.number().int().positive(),
            totalPages: z.number().int().nonnegative()
          })
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    404: {
      description: '父商品不存在',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

// 路由实现
export const publicGoodsChildrenRoutesMt = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  console.debug('publicGoodsChildrenRoutesMt handler被调用');
  try {
    console.debug('开始处理获取子商品列表请求');
    const { id: parentId } = c.req.valid('param');
    const query = c.req.valid('query');
    const { page, pageSize, keyword, sortBy, sortOrder } = query;

    // 验证父商品是否存在且是父商品（spuId=0）
    const parentGoods = await AppDataSource.getRepository(GoodsMt).findOne({
      where: { id: parentId, spuId: 0 } as any,
      select: ['id', 'tenantId']
    });

    if (!parentGoods) {
      return c.json({
        code: 404,
        message: '父商品不存在或不是有效的父商品'
      }, 404);
    }

    // 创建查询构建器
    const queryBuilder = AppDataSource.getRepository(GoodsMt)
      .createQueryBuilder('goods')
      .where('goods.spu_id = :spuId', { spuId: parentId })
      .andWhere('goods.state = :state', { state: 1 }) // 只获取可用的子商品
      .andWhere('goods.tenant_id = :tenantId', { tenantId: parentGoods.tenantId }); // 租户过滤

    // 搜索关键词过滤
    if (keyword) {
      queryBuilder.andWhere(
        '(goods.name LIKE :keyword OR goods.instructions LIKE :keyword)',
        { keyword: `%${keyword}%` }
      );
    }

    // 排序
    const orderBy = sortBy || 'createdAt';
    queryBuilder.orderBy(`goods.${orderBy}`, sortOrder);

    // 加载关联关系
    queryBuilder
      .leftJoinAndSelect('goods.category1', 'category1')
      .leftJoinAndSelect('goods.category2', 'category2')
      .leftJoinAndSelect('goods.category3', 'category3')
      .leftJoinAndSelect('goods.supplier', 'supplier')
      .leftJoinAndSelect('goods.merchant', 'merchant')
      .leftJoinAndSelect('goods.imageFile', 'imageFile')
      .leftJoinAndSelect('imageFile.uploadUser', 'imageUploadUser');

    // 分页
    const skip = (page - 1) * pageSize;
    queryBuilder.skip(skip).take(pageSize);

    // 获取子商品列表
    const children = await queryBuilder.getMany();
    const total = await queryBuilder.getCount();

    // 使用 parseWithAwait 确保数据格式正确
    try {
      const validatedChildren = await parseWithAwait(z.array(GoodsSchema), children);

      return c.json({
        data: validatedChildren,
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize)
      }, 200);
    } catch (validationError) {
      console.debug('Schema验证失败:', validationError);
      console.debug('验证数据:', children);
      if (validationError instanceof z.ZodError) {
        console.debug('Zod错误详情:', validationError.issues);
        return c.json({
          code: 400,
          message: '数据验证失败',
          issues: validationError.issues
        }, 400);
      }
      return c.json({
        code: 400,
        message: '数据验证失败',
        error: validationError instanceof Error ? validationError.message : '未知验证错误'
      }, 400);
    }
  } catch (error) {
    console.error('获取子商品列表失败:', error);
    return c.json({
      code: 500,
      message: error instanceof Error ? error.message : '获取子商品列表失败'
    }, 500);
  }
});