import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

const cosmosMock = {
  initializeAllContainers: vi.fn(),
  registerContainers: vi.fn(),
};

vi.mock('@bytelyst/cosmos', () => cosmosMock);

describe('initCosmosIfNeeded', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.unstubAllEnvs();
  });

  afterEach(() => {
    vi.resetModules();
  });

  it('registers containers and skips init in production by default', async () => {
    vi.stubEnv('COSMOS_ENDPOINT', 'https://example.documents.azure.com:443/');
    vi.stubEnv('COSMOS_KEY', 'key');
    vi.stubEnv('JWT_SECRET', 'secret');
    vi.stubEnv('NODE_ENV', 'production');
    vi.stubEnv('COSMOS_AUTO_INIT', 'false');

    const { initCosmosIfNeeded } = await import('./cosmos-init.js');
    await initCosmosIfNeeded();

    expect(cosmosMock.registerContainers).toHaveBeenCalledOnce();
    expect(cosmosMock.initializeAllContainers).not.toHaveBeenCalled();
  });

  it('initializes containers outside production and logs success', async () => {
    vi.stubEnv('COSMOS_ENDPOINT', 'https://example.documents.azure.com:443/');
    vi.stubEnv('COSMOS_KEY', 'key');
    vi.stubEnv('JWT_SECRET', 'secret');
    vi.stubEnv('NODE_ENV', 'test');

    cosmosMock.initializeAllContainers.mockResolvedValue(undefined);
    const writeSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);

    const { initCosmosIfNeeded } = await import('./cosmos-init.js');
    await initCosmosIfNeeded();

    expect(cosmosMock.registerContainers).toHaveBeenCalledOnce();
    expect(cosmosMock.initializeAllContainers).toHaveBeenCalledOnce();
    expect(writeSpy).toHaveBeenCalledWith('[platform-service] Cosmos containers ensured\n');
  });

  it('logs warning when initialization fails', async () => {
    vi.stubEnv('COSMOS_ENDPOINT', 'https://example.documents.azure.com:443/');
    vi.stubEnv('COSMOS_KEY', 'key');
    vi.stubEnv('JWT_SECRET', 'secret');
    vi.stubEnv('NODE_ENV', 'test');

    cosmosMock.initializeAllContainers.mockRejectedValue(new Error('boom'));
    const writeSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);

    const { initCosmosIfNeeded } = await import('./cosmos-init.js');
    await initCosmosIfNeeded();

    expect(cosmosMock.registerContainers).toHaveBeenCalledOnce();
    expect(cosmosMock.initializeAllContainers).toHaveBeenCalledOnce();
    expect(writeSpy).toHaveBeenCalledWith('[platform-service] Cosmos init failed: boom\n');
  });
});
