import { gym_socio_origen } from '@prisma/client';
import * as XLSX from 'xlsx';
import { ImportarSociosService } from './importar-socios.service';

/** Libro como los reales: otra hoja primero y una fila en blanco arriba del encabezado. */
function archivo(filas: unknown[][], encabezado = ['CLIENTE', 'C.I', 'MAIL', 'PHONE', 'PLAN'], celdas: Record<string, XLSX.CellObject> = {}): Express.Multer.File {
  const libro = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(libro, XLSX.utils.aoa_to_sheet([['COD', 'EMPRESA', 'Ruc'], ['1', 'Proveedor', '80000001-0']]), 'PROVEEDORES');
  const hoja = XLSX.utils.aoa_to_sheet([[], encabezado, ...filas]);
  Object.assign(hoja, celdas);
  XLSX.utils.book_append_sheet(libro, hoja, 'CLIENTES');
  const buffer = XLSX.write(libro, { type: 'buffer', bookType: 'xlsx' }) as Buffer;
  return { buffer, originalname: 'socios.xlsx' } as Express.Multer.File;
}

const EMPRESA = 'emp-1';

function crear(opts: { clientes?: Record<string, { id: string; nombre: string }>; socios?: Record<string, number>; sedes?: string[] } = {}) {
  const clientes = opts.clientes ?? {};
  const socios = opts.socios ?? {};
  let numero = 100;
  const creados: Record<string, unknown>[] = [];
  const fichas: Record<string, unknown>[] = [];
  const tx = {
    gym_config: { upsert: jest.fn().mockResolvedValue({}) },
    $queryRaw: jest.fn(() => Promise.resolve([{ numero: numero++ }])),
    gym_socios: {
      create: jest.fn(({ data }) => {
        fichas.push(data);
        return Promise.resolve({ id: `soc-${data.numero_socio}`, numero_socio: data.numero_socio });
      }),
    },
  };
  const prisma = {
    clientes: {
      findFirst: jest.fn(({ where }) => {
        const n = where.personas.OR[0].ruc;
        const c = clientes[n];
        return Promise.resolve(c ? { id: c.id, personas: { razon_social: c.nombre } } : null);
      }),
    },
    gym_socios: {
      findUnique: jest.fn(({ where }) => {
        const n = socios[where.empresa_id_cliente_id.cliente_id];
        return Promise.resolve(n ? { id: `soc-${n}`, numero_socio: n } : null);
      }),
    },
    gym_sedes: {
      findMany: jest.fn(() => Promise.resolve((opts.sedes ?? ['sede-1']).map((id) => ({ id })))),
      findFirst: jest.fn(({ where }) => Promise.resolve((opts.sedes ?? ['sede-1']).includes(where.id) ? { id: where.id } : null)),
    },
    gym_planes: { findMany: jest.fn().mockResolvedValue([{ id: 'plan-m', nombre: 'Mensual Libre', tipo: 'PERIODO' }]) },
    naturaleza_receptor: { findMany: jest.fn().mockResolvedValue([{ id: 'nat-contrib', codigo: 1 }, { id: 'nat-no', codigo: 2 }]) },
    tipo_documento_identidad: { findFirst: jest.fn().mockResolvedValue({ id: 'tdi-ci' }) },
    tipo_contribuyente: { findFirst: jest.fn().mockResolvedValue({ id: 'tc-pf' }) },
    tipo_operacion: { findMany: jest.fn().mockResolvedValue([{ id: 'op-b2b', codigo: 1 }, { id: 'op-b2c', codigo: 2 }]) },
    $transaction: jest.fn((fn: (t: typeof tx) => unknown) => fn(tx)),
  };
  const clientesService = {
    create: jest.fn((dto: Record<string, unknown>) => {
      if (dto.razon_social === 'FALLA AL CREAR') return Promise.reject(new Error('El RUC no existe'));
      creados.push(dto);
      return Promise.resolve({ data: { cliente: { id: `cli-${creados.length}` } } });
    }),
  };
  const audit = { log: jest.fn() };
  const manuales = {
    validar: jest.fn((_e: string, socio: string | null, _p: unknown, d: { fecha_inicio?: string; fecha_fin: string }) =>
      Promise.resolve(
        socio === 'soc-8'
          ? { ok: false, motivo: 'Ya tiene Mensual Libre del 01/11/2026 al 30/11/2026' }
          : { ok: true, fecha_inicio: d.fecha_inicio ?? '2026-11-16', fecha_fin: d.fecha_fin, creditos_totales: null, creditos_usados: 0 },
      ),
    ),
    asignar: jest.fn().mockResolvedValue({ id: 'mem-1' }),
  };
  const service = new ImportarSociosService(prisma as never, clientesService as never, audit as never, manuales as never);
  return { service, prisma, clientesService, creados, fichas, audit, manuales };
}

describe('ImportarSociosService', () => {
  it('preview: busca la hoja de socios, clasifica cada fila y no escribe nada', async () => {
    const { service, clientesService, fichas } = crear({
      clientes: { '2222222': { id: 'cli-x', nombre: 'YA CLIENTE' }, '3333333': { id: 'cli-s', nombre: 'YA SOCIO' } },
      socios: { 'cli-s': 7 },
    });
    const r = await service.preview(
      archivo([
        ['Socio Nuevo', '1111111', 'a@b.com', '981000111', 'GYM SOCIO'],
        ['Socio Cliente', '2222222', '-', '-', 'PILATES'],
        ['Socio Viejo', '3333333', '', '', ''],
        ['Socio Repetido', '1111111', '', '', ''],
        ['Socio Sin Doc', '-', '', '', ''],
        [],
      ]),
      EMPRESA,
    );
    expect(r.data.hoja).toBe('CLIENTES');
    expect(r.data.resumen).toEqual({ total: 5, nuevos: 1, clientes_existentes: 1, ya_socios: 1, errores: 2, planes: 0 });
    // Plan sin vencimiento: la fila entra igual, sin plan, y lo avisa.
    expect(r.data.filas[0].avisos).toEqual([expect.stringMatching(/Falta el vencimiento del plan «GYM SOCIO»/)]);
    expect(r.data.filas.map((f) => [f.fila, f.resultado])).toEqual([
      [3, 'NUEVO'],
      [4, 'CLIENTE_EXISTENTE'],
      [5, 'YA_ES_SOCIO'],
      [6, 'ERROR'],
      [7, 'ERROR'],
    ]);
    expect(r.data.filas[3].motivo).toMatch(/fila 3/);
    expect(clientesService.create).not.toHaveBeenCalled();
    expect(fichas).toHaveLength(0);
  });

  it('importar: crea cliente por ClientesService (B2C con CI, B2B con RUC) y la ficha incompleta de migración', async () => {
    const { service, creados, fichas, audit } = crear({ clientes: { '2222222': { id: 'cli-x', nombre: 'YA CLIENTE' } } });
    const r = await service.importar(
      archivo([
        ['Socio Ci', '1111111', 'a@b.com', '981000111', ''],
        ['Socio Ruc', '80144315-6', '', '', ''],
        ['Socio Cliente', '2222222', '', '', ''],
      ]),
      EMPRESA,
      undefined,
      'usr-1',
    );
    expect(r.data.resumen).toMatchObject({ nuevos: 2, clientes_existentes: 1, errores: 0 });
    expect(creados[0]).toMatchObject({
      razon_social: 'SOCIO CI',
      naturaleza_id: 'nat-no',
      tipo_operacion_id: 'op-b2c',
      nro_documento: '1111111',
      tipo_documento_id: 'tdi-ci',
      email: 'a@b.com',
      celular: '0981000111',
    });
    expect(creados[0].ruc).toBeUndefined();
    expect(creados[1]).toMatchObject({ naturaleza_id: 'nat-contrib', tipo_operacion_id: 'op-b2b', ruc: '80144315', dv: 6, tipo_contribuyente_id: 'tc-pf' });
    expect(creados).toHaveLength(2); // el cliente existente no se vuelve a crear
    expect(fichas.map((f) => f.cliente_id)).toEqual(['cli-1', 'cli-2', 'cli-x']);
    expect(fichas[0]).toMatchObject({
      empresa_id: EMPRESA,
      ficha_incompleta: true,
      origen: gym_socio_origen.MIGRACION,
      sede_base_id: 'sede-1',
      numero_socio: 100,
      telefono: '0981000111',
    });
    expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ empresa_id: EMPRESA, entity_type: 'gym_socios' }));
  });

  it('una fila que falla al crear no frena a las demás', async () => {
    const { service, fichas } = crear();
    const r = await service.importar(
      archivo([
        ['Falla al crear', '1111111', '', '', ''],
        ['Socio Bien', '4444444', '', '', ''],
      ]),
      EMPRESA,
      undefined,
    );
    expect(r.data.resumen).toMatchObject({ nuevos: 1, errores: 1 });
    expect(r.data.no_importadas[0]).toMatchObject({ fila: 3, resultado: 'ERROR', motivo: 'El RUC no existe' });
    expect(fichas).toHaveLength(1);
  });

  it('con más de una sede hay que elegir; una sede ajena se rechaza', async () => {
    const { service } = crear({ sedes: ['sede-1', 'sede-2'] });
    const f = archivo([['Socio Uno', '1111111', '', '', '']]);
    await expect(service.importar(f, EMPRESA, undefined)).rejects.toThrow(/más de una sede/);
    await expect(service.importar(f, EMPRESA, 'sede-9')).rejects.toThrow(/no existe/);
    await expect(service.importar(f, EMPRESA, 'sede-2')).resolves.toBeDefined();
  });

  it('un archivo sin columnas de nombre y documento se rechaza con un mensaje claro', async () => {
    const { service } = crear();
    const libro = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(libro, XLSX.utils.aoa_to_sheet([['A', 'B'], ['1', '2']]), 'Hoja1');
    const f = { buffer: XLSX.write(libro, { type: 'buffer', bookType: 'xlsx' }), originalname: 'x.xlsx' } as Express.Multer.File;
    await expect(service.preview(f, EMPRESA)).rejects.toThrow(/columnas de nombre y documento/);
  });

  it('plan ya pagado: se carga sin factura (MIGRACION) a los nuevos y a los que ya eran socios; lo que no cierra, avisa', async () => {
    const { service, manuales } = crear({
      clientes: { '3333333': { id: 'cli-s', nombre: 'YA SOCIO' }, '5555555': { id: 'cli-o', nombre: 'OTRO SOCIO' } },
      socios: { 'cli-s': 7, 'cli-o': 8 },
    });
    const enc = ['CLIENTE', 'C.I', 'PLAN', 'VENCE'];
    const filas = [
      ['Socio Nuevo', '1111111', 'mensual libre', 'se reemplaza por una fecha de Excel'],
      ['Ya Socio', '3333333', 'Mensual Libre', '30/11/2026'],
      ['Otro Socio', '5555555', 'Mensual Libre', '30/11/2026'],
      ['Plan Raro', '6666666', 'Zumba VIP', '30/11/2026'],
    ];
    // Una fecha de verdad de Excel (15/12/2026) con el formato por defecto, que se muestra mes/día.
    const fecha = { D3: { t: 'n', v: 46371, z: 'm/d/yy' } as XLSX.CellObject };
    const previa = await service.preview(archivo(filas, enc, fecha), EMPRESA);
    expect(previa.data.resumen).toMatchObject({ nuevos: 2, ya_socios: 2, planes: 2 });
    expect(previa.data.filas[0].plan_carga).toMatchObject({ plan_id: 'plan-m', fecha_fin: '2026-12-15' });
    expect(previa.data.filas[1].motivo).toMatch(/se le carga el plan/);
    expect(previa.data.filas[2].avisos[0]).toMatch(/Ya tiene Mensual Libre.*se importa sin plan/);
    expect(previa.data.filas[3].avisos[0]).toMatch(/No hay un plan activo llamado «Zumba VIP»/);
    expect(manuales.asignar).not.toHaveBeenCalled();

    const r = await service.importar(archivo(filas, enc, fecha), EMPRESA, undefined, 'usr-1');
    expect(r.data.resumen).toMatchObject({ planes: 2 });
    expect(manuales.asignar).toHaveBeenCalledTimes(2);
    expect(manuales.asignar).toHaveBeenCalledWith(
      EMPRESA,
      'soc-7',
      expect.objectContaining({ plan_id: 'plan-m', fecha_fin: '2026-11-30', motivo: expect.stringMatching(/importado de la planilla «socios.xlsx»/) }),
      'usr-1',
      'MIGRACION',
    );
    // El que ya era socio y recibió el plan no figura entre las no importadas; el que no pudo, sí.
    expect(r.data.no_importadas.map((f) => f.fila)).toEqual([5]);
  });
});
