/**
 * ASL 筛选项目控制器
 */

import { FastifyRequest, FastifyReply } from 'fastify';
import { CreateScreeningProjectDto } from '../types/index.js';
import { prisma } from '../../../config/database.js';
import { logger } from '../../../common/logging/index.js';

/**
 * 创建筛选项目
 */
export async function createProject(
  request: FastifyRequest<{ Body: CreateScreeningProjectDto & { userId?: string } }>,
  reply: FastifyReply
) {
  try {
    // 临时测试模式：优先从JWT获取，否则从请求体获取
    const userId = (request as any).userId || (request.body as any).userId || 'asl-test-user-001';
    const { projectName, picoCriteria, inclusionCriteria, exclusionCriteria, screeningConfig } = request.body;

    // 验证必填字段
    if (!projectName || !picoCriteria || !inclusionCriteria || !exclusionCriteria) {
      return reply.status(400).send({
        error: 'Missing required fields',
      });
    }

    // 创建项目
    const project = await prisma.aslScreeningProject.create({
      data: {
        userId,
        projectName,
        picoCriteria,
        inclusionCriteria,
        exclusionCriteria,
        screeningConfig: screeningConfig || {
          models: ['deepseek-chat', 'qwen-max'],
          temperature: 0,
        },
        status: 'draft',
      },
    });

    logger.info('ASL screening project created', {
      projectId: project.id,
      userId,
      projectName,
    });

    return reply.status(201).send({
      success: true,
      data: project,
    });
  } catch (error) {
    logger.error('Failed to create ASL project', { error });
    return reply.status(500).send({
      error: 'Failed to create project',
    });
  }
}

/**
 * 获取用户的所有筛选项目
 */
export async function getProjects(request: FastifyRequest, reply: FastifyReply) {
  try {
    const userId = (request as any).userId || 'asl-test-user-001';

    const projects = await prisma.aslScreeningProject.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
      include: {
        _count: {
          select: {
            literatures: true,
            screeningResults: true,
          },
        },
      },
    });

    return reply.send({
      success: true,
      data: projects,
    });
  } catch (error) {
    logger.error('Failed to get ASL projects', { error });
    return reply.status(500).send({
      error: 'Failed to get projects',
    });
  }
}

/**
 * 获取单个项目详情
 */
export async function getProjectById(
  request: FastifyRequest<{ Params: { projectId: string } }>,
  reply: FastifyReply
) {
  try {
    const userId = (request as any).userId || 'asl-test-user-001';
    const { projectId } = request.params;

    const project = await prisma.aslScreeningProject.findFirst({
      where: {
        id: projectId,
        userId,
      },
      include: {
        _count: {
          select: {
            literatures: true,
            screeningResults: true,
            screeningTasks: true,
          },
        },
      },
    });

    if (!project) {
      return reply.status(404).send({
        error: 'Project not found',
      });
    }

    return reply.send({
      success: true,
      data: project,
    });
  } catch (error) {
    logger.error('Failed to get ASL project', { error });
    return reply.status(500).send({
      error: 'Failed to get project',
    });
  }
}

/**
 * 更新项目
 */
export async function updateProject(
  request: FastifyRequest<{
    Params: { projectId: string };
    Body: Partial<CreateScreeningProjectDto>;
  }>,
  reply: FastifyReply
) {
  try {
    const userId = (request as any).userId || 'asl-test-user-001';
    const { projectId } = request.params;
    const updateData = request.body;

    // 验证项目归属
    const existingProject = await prisma.aslScreeningProject.findFirst({
      where: { id: projectId, userId },
    });

    if (!existingProject) {
      return reply.status(404).send({
        error: 'Project not found',
      });
    }

    const project = await prisma.aslScreeningProject.update({
      where: { id: projectId },
      data: updateData,
    });

    logger.info('ASL project updated', { projectId, userId });

    return reply.send({
      success: true,
      data: project,
    });
  } catch (error) {
    logger.error('Failed to update ASL project', { error });
    return reply.status(500).send({
      error: 'Failed to update project',
    });
  }
}

/**
 * 删除项目
 */
export async function deleteProject(
  request: FastifyRequest<{ Params: { projectId: string } }>,
  reply: FastifyReply
) {
  try {
    const userId = (request as any).userId || 'asl-test-user-001';
    const { projectId } = request.params;

    // 验证项目归属
    const existingProject = await prisma.aslScreeningProject.findFirst({
      where: { id: projectId, userId },
    });

    if (!existingProject) {
      return reply.status(404).send({
        error: 'Project not found',
      });
    }

    await prisma.aslScreeningProject.delete({
      where: { id: projectId },
    });

    logger.info('ASL project deleted', { projectId, userId });

    return reply.send({
      success: true,
      message: 'Project deleted successfully',
    });
  } catch (error) {
    logger.error('Failed to delete ASL project', { error });
    return reply.status(500).send({
      error: 'Failed to delete project',
    });
  }
}

