import { NotFoundException } from '@nestjs/common';
import { REQUIRE_PERMISSION_KEY } from 'src/auth/decorators/require-permission.decorator';
import { PuntoExpedicionesController } from './punto-expediciones.controller';
import { PuntoExpedicionesService } from './punto-expediciones.service';

/**
 * Mismo agujero que sucursales/cajas (E2E 2026-10-25): los puntos de expedición
 * se buscaban, editaban, activaban, marcaban predeterminados y borraban solo por
 * id, y el alta/edición tomaba el empresa_id del cuerpo.
 */
const PUNTO = { id: 'pe-1', empresa_id: 'emp-1', sucursal_id: 'suc-1', caja_id: 'caja-1', punto_expedicion: '002', active: true, es_default: false };

const crear = () => {
  const prisma: any = {
    empresas_puntos_expedicion: {
      findFirst: jest.fn(({ where }: any) =>
        Promise.resolve(where.id === PUNTO.id && where.empresa_id === 'emp-1' ? PUNTO : where.id ? null : null),
      ),
      findMany: jest.fn().mockResolvedValue([]),
      count: jest.fn().mockResolvedValue(0),
      create: jest.fn(({ data }: any) => Promise.resolve({ id: 'nuevo', ...data })),
      update: jest.fn(({ data }: any) => Promise.resolve({ ...PUNTO, ...data })),
      updateMany: jest.fn(),
      delete: jest.fn(),
    },
    empresas_sucursales: {
      findFirst: jest.fn(({ where }: any) => Promise.resolve(where.empresa_id === 'emp-1' && where.id === 'suc-1' ? { id: 'suc-1' } : null)),
    },
    cajas: { findFirst: jest.fn(({ where }: any) => Promise.resolve(where.id === 'caja-1' && where.sucursal_id === 'suc-1' ? { id: 'caja-1' } : null)) },
    $transaction: jest.fn((ops: any[]) => Promise.all(ops)),
  };
  const service = new PuntoExpedicionesService({} as any, {} as any, prisma, { log: jest.fn() } as any);
  return { service, prisma };
};

describe('Puntos de expedición — filtro por empresa del token', () => {
  it('leer un punto ajeno → 404; listar y por caja filtran por empresa', async () => {
    const { service, prisma } = crear();
    await expect(service.findOne('pe-1', 'emp-2')).rejects.toBeInstanceOf(NotFoundException);
    await service.findAll(1, 10, 'emp-1', 'suc-1');
    expect(prisma.empresas_puntos_expedicion.findMany.mock.calls[0][0].where).toEqual({ empresa_id: 'emp-1', sucursal_id: 'suc-1' });
    await service.findByCaja('caja-x', 'emp-1');
    expect(prisma.empresas_puntos_expedicion.findMany.mock.calls[1][0].where).toEqual({ caja_id: 'caja-x', empresa_id: 'emp-1' });
  });

  it('sin empresa en el token no devuelve nada', async () => {
    const { service } = crear();
    await expect(service.findAll(1, 10, undefined)).rejects.toBeInstanceOf(NotFoundException);
    await expect(service.findByCaja('c', undefined)).rejects.toBeInstanceOf(NotFoundException);
  });

  it('editar, activar, predeterminado y borrar un punto ajeno → 404 sin tocar nada', async () => {
    const { service, prisma } = crear();
    await expect(service.update('pe-1', { descripcion: 'x' }, 'emp-2', 'u')).rejects.toBeInstanceOf(NotFoundException);
    await expect(service.activarDesactivar('pe-1', 'emp-2', 'u')).rejects.toBeInstanceOf(NotFoundException);
    await expect(service.setDefault('pe-1', 'emp-2', 'u')).rejects.toBeInstanceOf(NotFoundException);
    await expect(service.unsetDefault('pe-1', 'emp-2', 'u')).rejects.toBeInstanceOf(NotFoundException);
    await expect(service.remove('pe-1', 'emp-2', 'u')).rejects.toBeInstanceOf(NotFoundException);
    expect(prisma.empresas_puntos_expedicion.update).not.toHaveBeenCalled();
    expect(prisma.empresas_puntos_expedicion.delete).not.toHaveBeenCalled();
  });

  it('editar no muda el punto de empresa ni a una sucursal/caja ajena', async () => {
    const { service, prisma } = crear();
    await service.update('pe-1', { descripcion: 'Mostrador', empresa_id: 'emp-2' } as any, 'emp-1', 'u');
    expect(prisma.empresas_puntos_expedicion.update.mock.calls[0][0].data.empresa_id).toBeUndefined();
    await expect(service.update('pe-1', { sucursal_id: 'suc-ajena' } as any, 'emp-1', 'u')).rejects.toBeInstanceOf(NotFoundException);
    await expect(service.update('pe-1', { caja_id: 'caja-ajena' } as any, 'emp-1', 'u')).rejects.toThrow(/misma sucursal/);
  });

  it('crear: la empresa sale del token; sucursal o caja ajena → 404', async () => {
    const { service, prisma } = crear();
    await service.create({ empresa_id: 'emp-2', sucursal_id: 'suc-1', caja_id: 'caja-1', punto_expedicion: '005' } as any, 'emp-1', 'u');
    expect(prisma.empresas_puntos_expedicion.create.mock.calls[0][0].data.empresa_id).toBe('emp-1');
    await expect(
      service.create({ empresa_id: 'emp-1', sucursal_id: 'suc-ajena', punto_expedicion: '006' } as any, 'emp-1', 'u'),
    ).rejects.toBeInstanceOf(NotFoundException);
    await expect(
      service.create({ empresa_id: 'emp-1', sucursal_id: 'suc-1', caja_id: 'caja-ajena', punto_expedicion: '006' } as any, 'emp-1', 'u'),
    ).rejects.toThrow(/misma sucursal/);
  });

  it('las escrituras piden «Editar sucursal»; las lecturas no piden permiso propio', () => {
    const p = PuntoExpedicionesController.prototype as any;
    for (const m of ['create', 'update', 'activarDesactivar', 'setDefault', 'unsetDefault', 'remove']) {
      expect(Reflect.getMetadata(REQUIRE_PERMISSION_KEY, p[m])).toEqual({ modulo: 'ADMINISTRACION', privilegio: 'ADM_SUC_SUCURSAL_EDITAR' });
    }
    for (const m of ['findAll', 'findByCaja', 'findOne']) {
      expect(Reflect.getMetadata(REQUIRE_PERMISSION_KEY, p[m])).toBeUndefined();
    }
  });
});
