import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';
import { GetProductsQuery } from './dto/get-products.query';

@Injectable()
export class ProductsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
  ) {}

  // Lists products with pagination and category filtering in tenant scope
  async list(ctx: RequestTenantContext, q: GetProductsQuery) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const page = Math.max(1, q.page || 1);
    const limit = Math.min(100, Math.max(1, q.limit || 25));
    const skip = (page - 1) * limit;

    const where: Prisma.ProductWhereInput = {
      tenantId,
    };

    if (q.category) {
      where.category = q.category;
    }

    if (typeof q.isActive === 'boolean') {
      where.isActive = q.isActive;
    }

    if (q.search?.trim()) {
      const term = q.search.trim();
      where.OR = [{ name: { contains: term } }, { sku: { contains: term } }, { description: { contains: term } }, { hsnSac: { contains: term } }];
    }

    const [total, data] = await Promise.all([
      this.prisma.product.count({ where }),
      this.prisma.product.findMany({
        where,
        skip,
        take: limit,
        orderBy: [{ isActive: 'desc' }, { name: 'asc' }],
        include: {
          _count: {
            select: { quoteItems: true, invoiceItems: true },
          },
        },
      }),
    ]);

    return {
      data,
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit) || 1,
      },
    };
  }

  // Retrieves product details by ID within tenant scope
  async get(ctx: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const product = await this.prisma.product.findFirst({
      where: { id, tenantId },
      include: {
        _count: {
          select: { quoteItems: true, invoiceItems: true },
        },
      },
    });

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

    return product;
  }

  // Creates a new product SKU within tenant scope
  async create(ctx: RequestTenantContext, dto: CreateProductDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const sku = dto.sku?.trim() || null;

    if (sku) {
      const existing = await this.prisma.product.findUnique({
        where: {
          tenantId_sku: {
            tenantId,
            sku,
          },
        },
      });

      if (existing) {
        throw new ConflictException(`A product with SKU "${sku}" already exists`);
      }
    }

    return this.prisma.product.create({
      data: {
        tenantId,
        name: dto.name.trim(),
        sku,
        category: dto.category || 'SERVICES',
        unit: dto.unit?.trim() || 'unit',
        price: dto.price ?? 0,
        gstRate: dto.gstRate ?? 18.0,
        hsnSac: dto.hsnSac?.trim() || null,
        description: dto.description?.trim() || null,
        isActive: dto.isActive ?? true,
      },
    });
  }

  // Updates product details and validates unique SKU
  async update(ctx: RequestTenantContext, id: string, dto: UpdateProductDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const existing = await this.get(ctx, id);

    if (dto.sku && dto.sku.trim() !== existing.sku) {
      const sku = dto.sku.trim();
      const duplicate = await this.prisma.product.findUnique({
        where: {
          tenantId_sku: {
            tenantId,
            sku,
          },
        },
      });

      if (duplicate && duplicate.id !== id) {
        throw new ConflictException(`A product with SKU "${sku}" already exists`);
      }
    }

    return this.prisma.product.update({
      where: { id: existing.id },
      data: {
        name: dto.name?.trim(),
        sku: dto.sku?.trim(),
        category: dto.category,
        unit: dto.unit?.trim(),
        price: dto.price,
        gstRate: dto.gstRate,
        hsnSac: dto.hsnSac !== undefined ? dto.hsnSac?.trim() || null : undefined,
        description: dto.description !== undefined ? dto.description?.trim() || null : undefined,
        isActive: dto.isActive,
      },
    });
  }

  // Deletes an unreferenced product from the catalog
  async delete(ctx: RequestTenantContext, id: string) {
    const product = await this.get(ctx, id);

    if (product._count.quoteItems > 0 || product._count.invoiceItems > 0) {
      throw new BadRequestException('Cannot delete product referenced in existing quotes or invoices. Archive it instead by setting isActive to false.');
    }

    await this.prisma.product.delete({
      where: { id: product.id },
    });

    return { success: true, message: `Product "${product.name}" deleted successfully` };
  }
}
