import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { PurchaseDto } from './dto/purchase.dto';

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

  listProducts() {
    return this.prisma.product.findMany({ include: { inventory: true } });
  }

  async purchaseProduct(userId: number, dto: PurchaseDto) {
    const product = await this.prisma.product.findUnique({
      where: { id: dto.productId },
      include: { inventory: true },
    });

    if (!product) {
      throw new NotFoundException('Product not found');
    }

    if (!product.inventory || product.inventory.quantity < dto.quantity) {
      throw new BadRequestException('Insufficient stock');
    }

    await this.prisma.$transaction([
      this.prisma.inventoryItem.update({
        where: { productId: dto.productId },
        data: { quantity: { decrement: dto.quantity } },
      }),
      this.prisma.order.create({
        data: {
          buyerId: userId,
          productId: dto.productId,
          quantity: dto.quantity,
          total: product.price.mul(dto.quantity),
        },
      }),
    ]);

    return { message: 'Purchase created successfully' };
  }
}
