import { gym_aviso_tipo as T, gym_renovacion_desde, Prisma } from '@prisma/client';
import { normalizarPlantillas } from '../config/config-gym.service';
import { valoresAviso } from './avisos-gym.service';
import {
  asuntoDesdePlantilla,
  errorPlantilla,
  htmlDesdePlantilla,
  parrafosDesdePlantilla,
  PLANTILLAS_POR_DEFECTO,
  plantillasEfectivas,
  textoSede,
} from './avisos-plantillas';

const SEDE = { nombre: 'Centro', direccion: 'Av. España 123', telefono: '021 555' };
const valores = (o: Partial<Parameters<typeof valoresAviso>[0]> = {}) =>
  valoresAviso({
    tipo: T.POR_VENCER,
    nombre: 'Ana <Gómez>',
    plan: 'Mensual',
    fechaFin: '2026-11-30',
    dias: 3,
    importe: 'Gs. 230.000',
    gimnasio: 'Gym Uno',
    sede: SEDE,
    renovacion: gym_renovacion_desde.FIN_ANTERIOR,
    ...o,
  });

describe('textos editables de los avisos de vencimiento', () => {
  it('sin editar, el texto original (el que salía antes)', () => {
    const v = valores();
    const p = plantillasEfectivas(null).POR_VENCER;
    expect(asuntoDesdePlantilla(p, v)).toBe('Tu cuota de Mensual vence el 30/11/2026');
    expect(parrafosDesdePlantilla(p, v)).toEqual([
      'Buen día, Ana <Gómez>.',
      'Tu plan Mensual vence el 30/11/2026.',
      'Importe de la renovación: Gs. 230.000.',
      'Recordá que la renovación cuenta desde la fecha de vencimiento.',
      'Podés renovarlo en la caja de Centro, Av. España 123 (tel. 021 555).',
    ]);
    expect(asuntoDesdePlantilla(plantillasEfectivas({}).VENCIDA, v)).toBe('Tu cuota de Mensual está vencida desde el 30/11/2026');
  });

  it('el párrafo con una variable vacía no sale (sin precio, sin «renovación desde el vencimiento»)', () => {
    const v = valores({ importe: '', renovacion: gym_renovacion_desde.FECHA_PAGO });
    const p = parrafosDesdePlantilla(PLANTILLAS_POR_DEFECTO.VENCE_HOY, v);
    expect(p.some((x) => x.includes('Importe'))).toBe(false);
    expect(p.some((x) => x.includes('Recordá'))).toBe(false);
    expect(p).toContain('Tu plan Mensual vence hoy, 30/11/2026.');
  });

  it('el texto editado reemplaza al original solo en ese aviso', () => {
    const editadas = plantillasEfectivas({ VENCIDA: { asunto: '{nombre}, ¡te extrañamos!', texto: 'Hace {dias} días venció tu {plan}.\nTe esperamos en {gimnasio}.' } });
    expect(editadas.POR_VENCER).toEqual(PLANTILLAS_POR_DEFECTO.POR_VENCER);
    const v = valores({ tipo: T.VENCIDA });
    expect(asuntoDesdePlantilla(editadas.VENCIDA, v)).toBe('Ana <Gómez>, ¡te extrañamos!');
    const html = htmlDesdePlantilla(editadas.VENCIDA, v, 'https://panel/baja?t=x');
    // Escapado, con el salto de línea simple respetado, el gimnasio arriba y el link de baja abajo.
    expect(html).toContain('Hace 3 días venció tu Mensual.<br>Te esperamos en Gym Uno.');
    expect(html).toContain('<h2 style="margin:0 0 16px;color:#111827">Gym Uno</h2>');
    expect(html).toContain('href="https://panel/baja?t=x"');
    expect(htmlDesdePlantilla({ asunto: 'x', texto: 'Hola {nombre}' }, v, '#')).toContain('Hola Ana &lt;Gómez&gt;');
  });

  it('una variable que no existe, un texto vacío o demasiado largo no se guardan', () => {
    expect(errorPlantilla({ asunto: 'Hola {nombre}', texto: 'Vence el {vencimiento}' }, 'Aviso')).toMatch(/la variable \{vencimiento\} no existe/);
    expect(errorPlantilla({ asunto: ' ', texto: 'x' }, 'Aviso')).toMatch(/falta el asunto/);
    expect(errorPlantilla({ asunto: 'x', texto: 'y'.repeat(2001) }, 'Aviso')).toMatch(/más de 2000/);
    expect(errorPlantilla(PLANTILLAS_POR_DEFECTO.VENCIDA, 'Aviso')).toBeNull();
  });

  it('al guardar: solo lo que difiere del original; todo original (o null) = vuelve al original', () => {
    expect(normalizarPlantillas(null)).toBe(Prisma.DbNull);
    expect(normalizarPlantillas({ ...PLANTILLAS_POR_DEFECTO })).toBe(Prisma.DbNull);
    const editado = { asunto: 'Vence tu {plan}', texto: 'Hola {nombre}\r\n\r\nNos vemos.' };
    expect(normalizarPlantillas({ ...PLANTILLAS_POR_DEFECTO, POR_VENCER: editado })).toEqual({ POR_VENCER: { asunto: 'Vence tu {plan}', texto: 'Hola {nombre}\n\nNos vemos.' } });
    expect(() => normalizarPlantillas({ VENCE_HOY: { asunto: 'x {foo}', texto: 'y' } })).toThrow(/Aviso «vence hoy»: la variable \{foo\} no existe/);
  });

  it('la sede como la lee el socio; sin sede, el gimnasio', () => {
    expect(textoSede(null, 'Gym Uno')).toBe('Gym Uno');
    expect(textoSede({ nombre: 'Norte', direccion: null, telefono: null }, 'Gym Uno')).toBe('Norte');
  });
});
