import { TenantConfigService } from "./tenant-config.service";
import { TenantConfig } from "./entities/tenant-config.entity";

function createService(overrides: Record<string, any> = {}) {
  const existing: TenantConfig = {
    id: 1,
    tenantId: 42,
    tenant: undefined as any,
    whatsappPhoneNumberId: null,
    whatsappAccessTokenEncrypted: null,
    whatsappTemplateLanguage: null,
    whatsappTemplateCotizacion: null,
    whatsappTemplateEstado: null,
    whatsappDefaultCountryCode: null,
    permiteTiendas: true,
    permiteProductosPropios: true,
    facturaHabilitada: true,
  };

  const repo = {
    findOne: jest.fn(async () => existing),
    update: jest.fn(async () => undefined),
    create: jest.fn((data: any) => ({ ...data })),
    save: jest.fn(async (data: any) => ({ id: 99, ...data })),
    ...overrides.repo,
  };

  const service = new TenantConfigService(repo as any);
  return { service, repo, existing };
}

describe("TenantConfigService", () => {
  it("findByTenantId busca por tenantId", async () => {
    const { service, repo, existing } = createService();

    const result = await service.findByTenantId(42);

    expect(result).toEqual(existing);
    expect(repo.findOne).toHaveBeenCalledWith({ where: { tenantId: 42 } });
  });

  it("getTogglesOperativos devuelve los valores guardados si ya existe una fila", async () => {
    const { service } = createService({
      repo: { findOne: jest.fn(async () => ({ permiteTiendas: false, permiteProductosPropios: true, facturaHabilitada: false })) },
    });

    const result = await service.getTogglesOperativos(42);

    expect(result).toEqual({ permiteTiendas: false, permiteProductosPropios: true, facturaHabilitada: false });
  });

  it("getTogglesOperativos default a todo true cuando el tenant no tiene fila en tenant_config", async () => {
    const { service } = createService({ repo: { findOne: jest.fn(async () => null) } });

    const result = await service.getTogglesOperativos(42);

    expect(result).toEqual({ permiteTiendas: true, permiteProductosPropios: true, facturaHabilitada: true });
  });

  it("updateTogglesOperativos actualiza la fila existente", async () => {
    const { service, repo, existing } = createService();

    await service.updateTogglesOperativos(42, { permiteTiendas: false });

    expect(repo.update).toHaveBeenCalledWith(existing.id, { permiteTiendas: false });
    expect(repo.create).not.toHaveBeenCalled();
  });

  it("updateTogglesOperativos crea la fila si el tenant todavia no tiene tenant_config", async () => {
    const { service, repo } = createService({ repo: { findOne: jest.fn(async () => null) } });

    await service.updateTogglesOperativos(42, { facturaHabilitada: false });

    expect(repo.create).toHaveBeenCalledWith({ tenantId: 42, facturaHabilitada: false });
    expect(repo.save).toHaveBeenCalled();
  });
});
