import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { SolutionChapterSchema } from '@/server/modules/solution-designs/solution-design.schema';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AppDataSource } from '@/server/data-source';
import { SolutionDesignService } from '@/server/modules/solution-designs/solution-design.service';
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';

// 路径参数Schema
const ChaptersParams = z.object({
  id: z.string().openapi({
    param: { name: 'id', in: 'path' },
    example: '1',
    description: '方案设计ID'
  })
});

// 响应Schema
const ChaptersResponse = z.object({
  data: z.array(SolutionChapterSchema),
  total: z.number().openapi({ example: 5, description: '总章节数' }),
  completed: z.number().openapi({ example: 3, description: '已完成章节数' })
});

// 路由定义
const routeDef = createRoute({
  method: 'get',
  path: '/{id}/chapters',
  middleware: [authMiddleware],
  request: {
    params: ChaptersParams
  },
  responses: {
    200: {
      description: '成功获取章节列表',
      content: { 'application/json': { schema: ChaptersResponse } }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '方案设计不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 路由实现
const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const { id } = c.req.valid('param');
    const user = c.get('user');
    
    const service = new SolutionDesignService(AppDataSource);
    
    // 先检查权限
    const existingDesign = await service.getById(Number(id));
    if (!existingDesign) {
      return c.json({ code: 404, message: '方案设计不存在' }, 404);
    }

    if (existingDesign.userId !== user.id) {
      return c.json({ code: 403, message: '无权访问此方案设计' }, 403);
    }

    // 获取章节列表
    const chapters = await service.getChapters(Number(id));
    
    // 统计完成情况
    const completedCount = chapters.filter(chapter => chapter.status === 'completed').length;

    return c.json({
      data: chapters,
      total: chapters.length,
      completed: completedCount
    }, 200);

  } catch (error) {
    console.error('获取章节列表失败:', error);
    const { code = 500, message = '获取章节列表失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code);
  }
});

export default app;