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: { inventoryAdjustments: true } });
  }

  async purchaseProduct(buyerId: string, dto: PurchaseDto) {
    const product = await this.prisma.product.findUnique({
      where: { id: dto.productId },
    });

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

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

    const totalCents = product.priceCents * BigInt(dto.quantity);

    // Create Order with OrderItem and decrement stock
    await this.prisma.$transaction([
      this.prisma.product.update({
        where: { id: dto.productId },
        data: { stock: { decrement: dto.quantity } },
      }),
      this.prisma.order.create({
        data: {
          buyerId: buyerId,
          sellerId: product.sellerId,
          totalCents: totalCents,
          status: 'PENDING',
          items: {
            create: {
              productId: dto.productId,
              quantity: BigInt(dto.quantity),
              unitCents: product.priceCents,
              batch: product.batch,
              expiresAt: product.expiresAt,
            },
          },
        },
      }),
    ]);

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

