/** Mocks compartidos de los specs del servicio de ofertas (solo tests). */
import { OfertasService } from './ofertas.service';

export const EMPRESA = 'e1';
export const ID = '0f6b8f1e-1d2c-4a3b-9c8d-7e6f5a4b3c2d';
export const OTRA_ID = '1f6b8f1e-1d2c-4a3b-9c8d-7e6f5a4b3c2d';
export const SUC = '2f6b8f1e-1d2c-4a3b-9c8d-7e6f5a4b3c2d';
export const REF = '3f6b8f1e-1d2c-4a3b-9c8d-7e6f5a4b3c2d';

export const filaOferta = (d: Record<string, unknown> = {}) => ({
  id: ID,
  empresa_id: EMPRESA,
  nombre: 'Promo',
  descripcion: 'desc',
  tipo: 'descuento_porcentaje',
  valor: 10,
  moneda: null,
  fecha_inicio: new Date('2026-11-01T11:00:00.000Z'),
  fecha_fin: new Date('2026-12-01T11:00:00.000Z'),
  prioridad: 1,
  acumulable_lista_precios: true,
  active: true,
  created_by: null,
  created_at: new Date('2026-11-01T11:00:00.000Z'),
  updated_at: new Date('2026-11-01T11:00:00.000Z'),
  oferta_aplicacion: [{ id: 'a1', oferta_id: ID, aplica_a: 'todos', referencia_id: null, excluir: false }],
  oferta_sucursales: [],
  _count: { oferta_usos: 0 },
  ...d,
});

export function crearServicio(opciones: { oferta?: any; monedas?: string[]; principal?: string } = {}) {
  const oferta = opciones.oferta === undefined ? filaOferta() : opciones.oferta;
  const contar = () => jest.fn(async ({ where }: any) => where.id.in.length);
  const tx: any = {
    oferta_aplicacion: { deleteMany: jest.fn(), createMany: jest.fn() },
    oferta_sucursales: { deleteMany: jest.fn(), createMany: jest.fn() },
    ofertas: { update: jest.fn(async ({ data }: any) => ({ ...oferta, ...data })) },
  };
  const prisma: any = {
    ofertas: {
      findFirst: jest.fn(async ({ where }: any) => (oferta && where.id === oferta.id && where.empresa_id === oferta.empresa_id ? oferta : null)),
      findMany: jest.fn(async () => []),
      count: jest.fn(async () => 0),
      create: jest.fn(async ({ data }: any) => filaOferta({ ...data, oferta_aplicacion: data.oferta_aplicacion.create })),
      update: jest.fn(async ({ data }: any) => ({ ...oferta, ...data })),
    },
    productos: { count: contar(), findMany: jest.fn(async () => []) },
    categorias: { count: contar(), findMany: jest.fn(async () => []) },
    marcas: { count: contar(), findMany: jest.fn(async () => []) },
    empresas_sucursales: { count: contar() },
    oferta_usos: { findMany: jest.fn(async () => []) },
    empresa_monedas: {
      findMany: jest.fn(async () => (opciones.monedas ?? ['PYG', 'USD']).map((codigo) => ({ moneda: { codigo } }))),
      findFirst: jest.fn(async () => ({ moneda: { codigo: opciones.principal ?? 'PYG' } })),
    },
    $transaction: jest.fn(async (arg: any) => (typeof arg === 'function' ? arg(tx) : Promise.all(arg))),
  };
  const audit = { log: jest.fn() };
  const cache = { set: jest.fn(async () => undefined) };
  const service = new OfertasService(prisma, audit as any, cache as any);
  return { service, prisma, tx, audit, cache };
}
