import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateProjectDto } from './dto/create-project.dto';
import { UpdateProjectDto } from './dto/update-project.dto';

@Injectable()
export class ProjectService {
  constructor(private readonly prisma: PrismaService) {}

  async create(productId: string, dto: CreateProjectDto) {
    await this.ensureProductExists(productId);
    return this.prisma.project.create({
      data: {
        productId,
        name: dto.name,
        description: dto.description ?? '',
      },
    });
  }

  findAll(productId: string) {
    return this.prisma.project.findMany({
      where: { productId },
      orderBy: { createdAt: 'desc' },
    });
  }

  async update(productId: string, projectId: string, dto: UpdateProjectDto) {
    await this.ensureProjectInProduct(productId, projectId);
    return this.prisma.project.update({
      where: { id: projectId },
      data: {
        ...(dto.name !== undefined && { name: dto.name }),
        ...(dto.description !== undefined && { description: dto.description }),
      },
    });
  }

  async remove(productId: string, projectId: string) {
    await this.ensureProjectInProduct(productId, projectId);
    return this.prisma.project.delete({ where: { id: projectId } });
  }

  private async ensureProductExists(productId: string) {
    const product = await this.prisma.product.findUnique({ where: { id: productId } });
    if (!product) throw new NotFoundException('产品不存在');
  }

  private async ensureProjectInProduct(productId: string, projectId: string) {
    const project = await this.prisma.project.findFirst({ where: { id: projectId, productId } });
    if (!project) throw new NotFoundException('项目不存在');
  }
}
