import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { SifenPayloadService } from 'src/facturas/sifen-payload.service';
import { esReimpresion, exigirPrivilegioPos, PRIV_POS, VENTANA_IMPRESION_MIN } from 'src/facturas/permisos-pos';
import { parseYmdValida } from 'src/utils/utilidades';
import { armarTicketData } from './ticket-data';

const LIMITE_DEFECTO = 20;
const LIMITE_MAXIMO = 200;

@Injectable()
export class MobileFacturasService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly sifenPayload: SifenPayloadService,
  ) {}

  /** Facturas del vendedor vinculado al usuario (vendedores_cobradores.usuario_id). */
  async mias(empresaId: string, usuarioId: string, desde?: string, hasta?: string, limit?: number) {
    const vendedor = await this.prisma.vendedores_cobradores.findFirst({
      where: { usuario_id: usuarioId, empresa_id: empresaId, active: { not: false } },
      select: { id: true },
    });
    if (!vendedor) return { items: [], vendedor_cobrador_id: null };

    const where: any = { empresa_id: empresaId, vendedor_id: vendedor.id };
    const gte = parseYmdValida(desde, false);
    const lte = parseYmdValida(hasta, true);
    if (gte || lte) {
      where.dfeemide = {};
      if (gte) where.dfeemide.gte = gte;
      if (lte) where.dfeemide.lte = lte;
    }
    const take = limit ? Math.min(Math.max(Math.trunc(limit), 1), LIMITE_MAXIMO) : LIMITE_DEFECTO;

    const filas = await this.prisma.factura_cab.findMany({
      where,
      orderBy: [{ dfeemide: 'desc' }, { created_at: 'desc' }],
      take,
      select: {
        id: true,
        dest: true,
        dpunexp: true,
        dnumdoc: true,
        dfeemide: true,
        total_factura: true,
        estado: true,
        origen: true,
        clientes: { select: { personas: { select: { razon_social: true } } } },
        moneda: { select: { codigo: true } },
        condicion_operacion: { select: { descripcion: true } },
      },
    });

    return {
      items: filas.map((f) => ({
        id: f.id,
        numero: `${f.dest}-${f.dpunexp}-${f.dnumdoc}`,
        fecha: f.dfeemide,
        cliente: f.clientes?.personas?.razon_social ?? null,
        total: f.total_factura == null ? 0 : Number(f.total_factura),
        moneda: { codigo: f.moneda?.codigo ?? null },
        condicion: f.condicion_operacion?.descripcion ?? null,
        estado: f.estado,
        origen: f.origen,
      })),
      vendedor_cobrador_id: vendedor.id,
    };
  }

  /**
   * Datos del ticket KUDE. Pasados VENTANA_IMPRESION_MIN minutos desde la
   * emisión es una reimpresión y exige VEN_POS_REIMPRIMIR (igual que /kude/generate).
   */
  async ticketData(facturaId: string, empresaId: string, usuarioId: string) {
    const factura = await this.prisma.factura_cab.findFirst({
      where: { id: facturaId, empresa_id: empresaId },
      select: { id: true, created_at: true, dest: true },
    });
    if (!factura) throw new NotFoundException('Factura no encontrada');

    if (esReimpresion(factura.created_at)) {
      await exigirPrivilegioPos(
        this.prisma,
        usuarioId,
        PRIV_POS.REIMPRIMIR,
        `reimprimir el ticket (pasaron más de ${VENTANA_IMPRESION_MIN} minutos de la venta)`,
      );
    }

    const [payload, vendedor, empresa, sucursal, actividad, timbrado] = await Promise.all([
      this.sifenPayload.buildFacturaPayload(facturaId, empresaId),
      this.sifenPayload.vendedorFactura(facturaId, empresaId),
      this.prisma.empresas.findUnique({
        where: { id: empresaId },
        select: { ruc: true, dv: true, razon_social: true, nombre_fantasia: true, email: true },
      }),
      // Misma sucursal que resuelve el payload (establecimiento de la factura).
      factura.dest
        ? this.prisma.empresas_sucursales.findFirst({
            where: { empresa_id: empresaId, punto_establecimiento: factura.dest, active: true },
            select: { direccion: true, telefono: true, email: true, nombre_fantasia: true },
          })
        : null,
      // Solo la actividad principal (la primera con principal desc), como el KUDE.
      this.prisma.actividades_economicas.findFirst({
        where: { empresa_id: empresaId },
        orderBy: { principal: 'desc' },
        select: { desc_actividad: true },
      }),
      // Timbrado vigente: el último cargado de la empresa (generador-pdf/src/routes/kude/index.js).
      this.prisma.empresas_timbrado.findFirst({
        where: { empresa_id: empresaId },
        orderBy: { created_at: 'desc' },
        select: { num_timbrado: true, fecha_inicio: true },
      }),
    ]);
    if (!empresa) throw new ForbiddenException('Empresa no encontrada');

    return armarTicketData({
      payload,
      vendedor,
      empresa: { ...empresa, actividad_economica: actividad?.desc_actividad ?? '' },
      sucursal,
      timbrado,
    });
  }
}
