import { BadRequestException, ConflictException, Injectable, UnprocessableEntityException } from '@nestjs/common';
import { CreateProductoDto } from 'src/productos/dto/create-producto.dto';
import { ProductosService } from 'src/productos/productos.service';
import { PrismaService } from 'src/prisma/prisma.service';

/** Afectación "Gravado IVA" (SIFEN 1) y unidad "UNI" (SIFEN 77), como el alta de productos. */
const AFECTACION_GRAVADO = 1;
const UNIDAD_UNI = 77;

/**
 * El producto del ERP detrás de cada plan y servicio del gimnasio.
 *
 * El plan y el servicio se venden en el POS como cualquier producto, así que su
 * precio vive en el producto (o en la lista de precios), nunca en las tablas gym_.
 * Se crean con `ProductosService.create`, el mismo camino que la pantalla de
 * productos: control de plan, slug y auditoría incluidos.
 */
@Injectable()
export class ProductoGymService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly productos: ProductosService,
  ) {}

  /** Crea un producto tipo servicio, sin inventario, gravado 10 %, y devuelve su id. */
  async crear(nombre: string, precio: number, empresa_id: string, user_id?: string): Promise<string> {
    const [afectacion, unidad] = await Promise.all([
      this.prisma.afectacion_iva.findFirst({ where: { codigo: AFECTACION_GRAVADO }, select: { id: true } }),
      this.prisma.unidades_de_medida.findFirst({ where: { codigo: UNIDAD_UNI }, select: { id: true } }),
    ]);
    if (!afectacion || !unidad) {
      throw new UnprocessableEntityException('Falta la afectación "Gravado IVA" o la unidad "UNI" en el sistema');
    }
    const dto: CreateProductoDto = {
      descripcion: nombre,
      afectacion_id: afectacion.id,
      unidad_medida_id: unidad.id,
      precio,
      porcentaje_iva: 10,
      proporcion_iva: 100,
      tipo: 'servicio',
      maneja_inventario: false,
    };
    const { data } = await this.productos.create(dto, empresa_id, user_id);
    return data.id;
  }

  /** El producto existe en la empresa y no está dado de baja. */
  async validarExistente(producto_id: string, empresa_id: string, etiqueta = 'El producto') {
    const p = await this.prisma.productos.findFirst({
      where: { id: producto_id, empresa_id, deleted: false },
      select: { id: true },
    });
    if (!p) throw new BadRequestException(`${etiqueta} no existe en esta empresa`);
  }

  /**
   * Un producto es de un solo plan o servicio activo: si no, al venderlo en el POS
   * no se sabría qué membresía o servicio activar.
   */
  async validarLibre(producto_id: string, empresa_id: string, excepto?: { plan_id?: string; servicio_id?: string }) {
    const [plan, servicio] = await Promise.all([
      this.prisma.gym_planes.findFirst({
        where: { empresa_id, producto_id, activo: true, ...(excepto?.plan_id && { id: { not: excepto.plan_id } }) },
        select: { nombre: true },
      }),
      this.prisma.gym_servicios.findFirst({
        where: { empresa_id, producto_id, activo: true, ...(excepto?.servicio_id && { id: { not: excepto.servicio_id } }) },
        select: { nombre: true },
      }),
    ]);
    const ocupado = plan ? `el plan "${plan.nombre}"` : servicio ? `el servicio "${servicio.nombre}"` : null;
    if (ocupado) throw new ConflictException(`Ese producto ya se vende como ${ocupado}`);
  }

  /** Cambia el precio de referencia del producto por el camino normal (auditado). */
  async actualizarPrecio(producto_id: string, precio: number, empresa_id: string, user_id?: string) {
    await this.productos.update(producto_id, { precio }, empresa_id, user_id);
  }

  /** Renombra el producto para que el POS y la factura muestren el nombre del plan. */
  async renombrar(producto_id: string, descripcion: string, empresa_id: string, user_id?: string) {
    await this.productos.update(producto_id, { descripcion }, empresa_id, user_id);
  }
}
