import { Injectable } 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 ProductsService {
  constructor(private readonly prisma: PrismaService) {}

  async create(createProductDto: CreateProductDto) {
    const { schemes, addons, ...productData } = createProductDto;
    return this.prisma.product.create({
      data: {
        ...productData,
        schemes: schemes && schemes.length > 0 ? { create: schemes } : undefined,
        addons: addons && addons.length > 0 ? { create: addons } : undefined,
      },
      include: { schemes: true, addons: true },
    });
  }

  findAll() {
    return this.prisma.product.findMany({
      include: { schemes: true, addons: true },
    });
  }

  findOne(id: string) {
    return this.prisma.product.findUnique({
      where: { id },
      include: { schemes: true, addons: true },
    });
  }

  async update(id: string, updateProductDto: UpdateProductDto) {
    const { schemes, addons, ...productData } = updateProductDto;

    if (schemes) {
      await this.prisma.productScheme.deleteMany({ where: { productId: id } });
    }
    if (addons) {
      await this.prisma.productAddon.deleteMany({ where: { productId: id } });
    }

    return this.prisma.product.update({
      where: { id },
      data: {
        ...productData,
        schemes: schemes && schemes.length > 0 ? { create: schemes } : undefined,
        addons: addons && addons.length > 0 ? { create: addons } : undefined,
      },
      include: { schemes: true, addons: true },
    });
  }

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

  // ─── Per-User Discount Cap Methods ───────────────────────────────────────

  /** Get all user discount caps for a product (includes scheme-level caps too) */
  async getUserDiscounts(productId: string) {
    return this.prisma.userProductDiscount.findMany({
      where: { productId },
      include: {
        user: { select: { id: true, name: true, email: true, role: true } },
        scheme: { select: { id: true, name: true, price: true } },
      },
      orderBy: { createdAt: 'asc' },
    });
  }

  /**
   * Create or update a discount cap for a specific user on this product.
   * Pass schemeId to cap at the scheme/variation level; omit/null for product-level cap.
   */
  async upsertUserDiscount(
    productId: string,
    userId: string,
    maxDiscountPercentage: number,
    schemeId: string | null,
  ) {
    // Find existing record manually to avoid Prisma null composite-key issue
    const existing = await this.prisma.userProductDiscount.findFirst({
      where: { userId, productId, schemeId: schemeId ?? null },
    });

    if (existing) {
      return this.prisma.userProductDiscount.update({
        where: { id: existing.id },
        data: { maxDiscountPercentage },
        include: {
          user: { select: { id: true, name: true, email: true, role: true } },
          scheme: { select: { id: true, name: true, price: true } },
        },
      });
    }

    return this.prisma.userProductDiscount.create({
      data: {
        userId,
        productId,
        schemeId: schemeId ?? null,
        maxDiscountPercentage,
      },
      include: {
        user: { select: { id: true, name: true, email: true, role: true } },
        scheme: { select: { id: true, name: true, price: true } },
      },
    });
  }

  /** Delete a specific user discount cap by its record ID */
  async removeUserDiscount(discountId: string) {
    return this.prisma.userProductDiscount.delete({ where: { id: discountId } });
  }
}
