import { FastifyRequest, FastifyReply } from 'fastify';
import { projectService } from '../services/projectService.js';

interface ProjectParams {
  id: string;
}

interface CreateProjectBody {
  name: string;
  background: string;
  researchType: 'observational' | 'interventional';
}

interface UpdateProjectBody {
  name?: string;
  background?: string;
  researchType?: 'observational' | 'interventional';
}

class ProjectController {
  // 获取项目列表
  async getProjects(request: FastifyRequest, reply: FastifyReply) {
    try {
      // TODO: 从JWT token中获取真实的userId
      // 目前使用模拟用户ID
      const userId = 'user-mock-001';

      const projects = await projectService.getProjectsByUserId(userId);

      return reply.code(200).send({
        success: true,
        data: projects,
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '获取项目列表失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 获取单个项目详情
  async getProjectById(
    request: FastifyRequest<{ Params: ProjectParams }>,
    reply: FastifyReply
  ) {
    try {
      const { id } = request.params;
      const userId = 'user-mock-001'; // TODO: 从JWT获取

      const project = await projectService.getProjectById(id, userId);

      if (!project) {
        return reply.code(404).send({
          success: false,
          message: '项目不存在或无权访问',
        });
      }

      return reply.code(200).send({
        success: true,
        data: project,
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '获取项目详情失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 创建项目
  async createProject(request: FastifyRequest, reply: FastifyReply) {
    try {
      const body = request.body as CreateProjectBody;
      const userId = 'user-mock-001'; // TODO: 从JWT获取

      // 检查用户项目数量限制（可选）
      const projectCount = await projectService.countUserProjects(userId);
      const MAX_PROJECTS = 50; // 可以配置到环境变量

      if (projectCount >= MAX_PROJECTS) {
        return reply.code(400).send({
          success: false,
          message: `最多只能创建${MAX_PROJECTS}个项目`,
        });
      }

      const project = await projectService.createProject({
        name: body.name,
        background: body.background,
        researchType: body.researchType,
        userId,
      });

      return reply.code(201).send({
        success: true,
        message: '项目创建成功',
        data: project,
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '创建项目失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 更新项目
  async updateProject(
    request: FastifyRequest<{ Params: ProjectParams }>,
    reply: FastifyReply
  ) {
    try {
      const { id } = request.params;
      const body = request.body as UpdateProjectBody;
      const userId = 'user-mock-001'; // TODO: 从JWT获取

      const project = await projectService.updateProject(id, userId, body);

      if (!project) {
        return reply.code(404).send({
          success: false,
          message: '项目不存在或无权访问',
        });
      }

      return reply.code(200).send({
        success: true,
        message: '项目更新成功',
        data: project,
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '更新项目失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }

  // 删除项目
  async deleteProject(
    request: FastifyRequest<{ Params: ProjectParams }>,
    reply: FastifyReply
  ) {
    try {
      const { id } = request.params;
      const userId = 'user-mock-001'; // TODO: 从JWT获取

      const project = await projectService.deleteProject(id, userId);

      if (!project) {
        return reply.code(404).send({
          success: false,
          message: '项目不存在或无权访问',
        });
      }

      return reply.code(200).send({
        success: true,
        message: '项目删除成功',
      });
    } catch (error) {
      request.log.error(error);
      return reply.code(500).send({
        success: false,
        message: '删除项目失败',
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }
  }
}

export const projectController = new ProjectController();

