import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';

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

  create(dto: CreateProductDto) {
    return this.prisma.product.create({ data: dto });
  }

  findAll() {
    return this.prisma.product.findMany({
      orderBy: { createdAt: 'desc' },
      include: {
        _count: { select: { requirements: true, projects: true } },
      },
    });
  }

  findAllWithChildren() {
    return this.prisma.product.findMany({
      orderBy: { createdAt: 'desc' },
      include: {
        projects: {
          orderBy: { createdAt: 'desc' },
          select: { id: true, name: true, description: true, createdAt: true },
        },
        versions: {
          orderBy: { createdAt: 'desc' },
          select: { id: true, name: true, releaseDate: true, createdAt: true },
        },
        _count: { select: { requirements: true, projects: true, versions: true } },
      },
    });
  }

  async findOne(id: string) {
    const product = await this.prisma.product.findUnique({
      where: { id },
      include: {
        requirements: { orderBy: { createdAt: 'desc' } },
        versions: { orderBy: { createdAt: 'desc' } },
        _count: { select: { projects: true } },
      },
    });
    if (!product) throw new NotFoundException('产品不存在');
    return product;
  }

  async update(id: string, dto: UpdateProductDto) {
    await this.ensureExists(id);
    return this.prisma.product.update({ where: { id }, data: dto });
  }

  async remove(id: string) {
    await this.ensureExists(id);
    return this.prisma.product.delete({ where: { id } });
  }

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