import { NotFoundException } from '@nestjs/common';
import { TabletsGymService } from './tablets-gym.service';

const URL_LOGO = 'https://bucket.example.com/logos/76cfd8f5-3c8c-42ea-88eb-185aa579869f.png';

function servicio(logo: string | null) {
  const svc = new TabletsGymService({} as any, {} as any, {} as any, {} as any);
  jest.spyOn(svc as any, 'deCodigo').mockResolvedValue({
    nombre: 'Entrada',
    sede: { nombre: 'Centro' },
    empresas: { razon_social: 'Gym SA', nombre_fantasia: 'Gym', logo },
  });
  return svc;
}

const respuesta = (status: number, tipo: string, bytes = 10) =>
  Promise.resolve(new Response(new Uint8Array(bytes), { status, headers: { 'content-type': tipo } }));

describe('Tablet · logo del gimnasio', () => {
  afterEach(() => jest.restoreAllMocks());

  it('info dice si hay logo, pero nunca da la URL (lleva el id de la empresa, regla 10)', async () => {
    const r = await servicio(URL_LOGO).info('k');
    expect(r).toEqual({ gimnasio: 'Gym', sede: 'Centro', tablet: 'Entrada', logo: true });
    expect(JSON.stringify(r)).not.toContain('76cfd8f5');
    expect((await servicio(null).info('k')).logo).toBe(false);
  });

  it('logo entrega la imagen con su tipo', async () => {
    const f = jest.spyOn(global, 'fetch').mockImplementation(() => respuesta(200, 'image/png', 42));
    const r = await servicio(URL_LOGO).logo('k');
    expect(f).toHaveBeenCalledWith(URL_LOGO, expect.anything());
    expect(r.tipo).toBe('image/png');
    expect(r.contenido.length).toBe(42);
  });

  it('sin logo, con URL que no es https o con algo que no es imagen: 404', async () => {
    const f = jest.spyOn(global, 'fetch').mockImplementation(() => respuesta(200, 'text/html'));
    await expect(servicio(null).logo('k')).rejects.toBeInstanceOf(NotFoundException);
    await expect(servicio('http://169.254.169.254/x').logo('k')).rejects.toBeInstanceOf(NotFoundException);
    expect(f).not.toHaveBeenCalled();
    await expect(servicio(URL_LOGO).logo('k')).rejects.toBeInstanceOf(NotFoundException);
    f.mockImplementation(() => respuesta(403, 'image/png'));
    await expect(servicio(URL_LOGO).logo('k')).rejects.toBeInstanceOf(NotFoundException);
  });

  it('un logo de más de 3 MB no se reenvía', async () => {
    jest.spyOn(global, 'fetch').mockImplementation(() => respuesta(200, 'image/png', 3 * 1024 * 1024 + 1));
    await expect(servicio(URL_LOGO).logo('k')).rejects.toBeInstanceOf(NotFoundException);
  });
});
