import type { Logger } from '@core/shared/domain/Logger';
import { describe, expect, it, vi, type Mock } from 'vitest';
import type { IdentitySessionPort } from '../ports/IdentitySessionPort';
import { LogoutUseCase } from './LogoutUseCase';

describe('LogoutUseCase', () => {
  let sessionPort: {
    clearSession: Mock;
  };
  let logger: Logger & { error: Mock };
  let useCase: LogoutUseCase;

  beforeEach(() => {
    sessionPort = {
      clearSession: vi.fn(),
    };

    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger & { error: Mock };

    useCase = new LogoutUseCase(
      sessionPort as unknown as IdentitySessionPort,
      logger,
    );
  });

  it('successfully clears session and returns success', async () => {
    sessionPort.clearSession.mockResolvedValue(undefined);

    const result = await useCase.execute();

    expect(result.isOk()).toBe(true);
    const logoutResult = result.unwrap();
    expect(logoutResult.success).toBe(true);
    expect(sessionPort.clearSession).toHaveBeenCalledTimes(1);
  });

  it('returns error when session clear fails', async () => {
    sessionPort.clearSession.mockRejectedValue(new Error('Session clear failed'));

    const result = await useCase.execute();

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr().code).toBe('REPOSITORY_ERROR');
    expect(logger.error).toHaveBeenCalled();
  });
});