import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { UpsertUserProductDto } from './dto/upsert-user-product.dto';

const PRODUCT_INCLUDE = {
  product: {
    include: {
      nutrition: true,
      tags: { include: { tag: true } },
    },
  },
};

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

  findAll(userId: number) {
    return this.prisma.userProduct.findMany({
      where: { userId },
      include: PRODUCT_INCLUDE,
      orderBy: { updatedAt: 'desc' },
    });
  }

  findOne(userId: number, productId: number) {
    return this.prisma.userProduct.findUnique({
      where: { userId_productId: { userId, productId } },
      include: PRODUCT_INCLUDE,
    });
  }

  upsert(userId: number, dto: UpsertUserProductDto) {
    const { productId, ...data } = dto;
    return this.prisma.userProduct.upsert({
      where: { userId_productId: { userId, productId } },
      create: { userId, productId, ...data },
      update: data,
      include: PRODUCT_INCLUDE,
    });
  }

  remove(userId: number, productId: number) {
    return this.prisma.userProduct.delete({
      where: { userId_productId: { userId, productId } },
    });
  }
}
