import { describe, it, expect, vi, type Mock } from 'vitest';
import { SignupWithEmailUseCase } from './SignupWithEmailUseCase';
import type { SignupWithEmailInput } from './SignupWithEmailUseCase';
import type { IUserRepository, StoredUser } from '../../domain/repositories/IUserRepository';
import type { AuthSession, IdentitySessionPort } from '../ports/IdentitySessionPort';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';

type SignupWithEmailOutput = unknown;

describe('SignupWithEmailUseCase', () => {
  let userRepository: {
    findByEmail: Mock;
    create: Mock;
  };
  let sessionPort: {
    createSession: Mock;
    getCurrentSession: Mock;
    clearSession: Mock;
  };
  let logger: Logger;
  let output: UseCaseOutputPort<SignupWithEmailOutput> & { present: Mock };
  let useCase: SignupWithEmailUseCase;

  beforeEach(() => {
    userRepository = {
      findByEmail: vi.fn(),
      create: vi.fn(),
    };
    sessionPort = {
      createSession: vi.fn(),
      getCurrentSession: vi.fn(),
      clearSession: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger;
    output = {
      present: vi.fn(),
    };
    useCase = new SignupWithEmailUseCase(
      userRepository as unknown as IUserRepository,
      sessionPort as unknown as IdentitySessionPort,
      logger,
      output,
    );
  });

  it('creates a new user and session for valid input', async () => {
    const command: SignupWithEmailInput = {
      email: 'new@example.com',
      password: 'password123',
      displayName: 'New User',
    };

    userRepository.findByEmail.mockResolvedValue(null);

    const session: AuthSession = {
      user: {
        id: 'user-1',
        email: command.email.toLowerCase(),
        displayName: command.displayName,
      },
      issuedAt: Date.now(),
      expiresAt: Date.now() + 1000,
      token: 'session-token',
    };

    sessionPort.createSession.mockResolvedValue(session);

    const result = await useCase.execute(command);

    expect(userRepository.findByEmail).toHaveBeenCalledWith(command.email);
    expect(userRepository.create).toHaveBeenCalled();
    expect(sessionPort.createSession).toHaveBeenCalledWith({
      id: expect.any(String),
      email: command.email.toLowerCase(),
      displayName: command.displayName,
    });

    expect(result.isOk()).toBe(true);
    expect(output.present).toHaveBeenCalledWith({
      sessionToken: 'session-token',
      userId: 'user-1',
      displayName: 'New User',
      email: 'new@example.com',
      createdAt: expect.any(Date),
      isNewUser: true,
    });
  });

  it('returns error when email format is invalid', async () => {
    const command: SignupWithEmailInput = {
      email: 'invalid-email',
      password: 'password123',
      displayName: 'User',
    };

    const result = await useCase.execute(command);
    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr();
    expect(err.code).toBe('INVALID_EMAIL_FORMAT');
  });

  it('returns error when password is too short', async () => {
    const command: SignupWithEmailInput = {
      email: 'valid@example.com',
      password: 'short',
      displayName: 'User',
    };

    const result = await useCase.execute(command);
    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr();
    expect(err.code).toBe('WEAK_PASSWORD');
  });

  it('returns error when display name is too short', async () => {
    const command: SignupWithEmailInput = {
      email: 'valid@example.com',
      password: 'password123',
      displayName: ' ',
    };

    const result = await useCase.execute(command);
    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr();
    expect(err.code).toBe('INVALID_DISPLAY_NAME');
  });

  it('returns error when email already exists', async () => {
    const command: SignupWithEmailInput = {
      email: 'existing@example.com',
      password: 'password123',
      displayName: 'Existing User',
    };

    const existingUser: StoredUser = {
      id: 'user-1',
      email: command.email,
      displayName: command.displayName,
      passwordHash: 'hash',
      createdAt: new Date(),
    };

    userRepository.findByEmail.mockResolvedValue(existingUser);

    const result = await useCase.execute(command);
    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr();
    expect(err.code).toBe('EMAIL_ALREADY_EXISTS');
  });
});
