import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { User } from '../../domain/entities/User';
import type { AuthRepository } from '../../domain/repositories/AuthRepository';
import type { MagicLinkRepository } from '../../domain/repositories/MagicLinkRepository';
import { PasswordHash } from '../../domain/value-objects/PasswordHash';
import { UserId } from '../../domain/value-objects/UserId';
import type { MagicLinkNotificationPort } from '../ports/MagicLinkNotificationPort';
import { ForgotPasswordUseCase } from './ForgotPasswordUseCase';

describe('ForgotPasswordUseCase', () => {
  let authRepo: {
    findByEmail: Mock;
  };
  let magicLinkRepo: {
    checkRateLimit: Mock;
    createPasswordResetRequest: Mock;
  };
  let notificationPort: {
    sendMagicLink: Mock;
  };
  let logger: Logger;
  let useCase: ForgotPasswordUseCase;

  beforeEach(() => {
    authRepo = {
      findByEmail: vi.fn(),
    };

    magicLinkRepo = {
      checkRateLimit: vi.fn(),
      createPasswordResetRequest: vi.fn(),
    };

    notificationPort = {
      sendMagicLink: vi.fn(),
    };

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

    useCase = new ForgotPasswordUseCase(
      authRepo as unknown as AuthRepository,
      magicLinkRepo as unknown as MagicLinkRepository,
      notificationPort as unknown as MagicLinkNotificationPort,
      logger,
    );
  });

  it('generates and sends magic link when user exists', async () => {
    const user = User.create({
      id: UserId.create(),
      displayName: 'John Smith',
      email: 'test@example.com',
      passwordHash: PasswordHash.fromHash('hashed-password'),
    });
    authRepo.findByEmail.mockResolvedValue(user);
    magicLinkRepo.checkRateLimit.mockResolvedValue(Result.ok(undefined));

    const result = await useCase.execute({ email: 'test@example.com' });

    expect(result.isOk()).toBe(true);
    const forgotPasswordResult = result.unwrap();
    expect(forgotPasswordResult.message).toBe('Password reset link generated successfully');
    expect(forgotPasswordResult.magicLink).toBeDefined();
    expect(magicLinkRepo.createPasswordResetRequest).toHaveBeenCalled();
    expect(notificationPort.sendMagicLink).toHaveBeenCalled();
  });

  it('returns success even when user does not exist (for security)', async () => {
    authRepo.findByEmail.mockResolvedValue(null);
    magicLinkRepo.checkRateLimit.mockResolvedValue(Result.ok(undefined));

    const result = await useCase.execute({ email: 'nonexistent@example.com' });

    expect(result.isOk()).toBe(true);
    const forgotPasswordResult = result.unwrap();
    expect(forgotPasswordResult.message).toBe('If an account exists with this email, a password reset link will be sent');
    expect(forgotPasswordResult.magicLink).toBeNull();
    expect(magicLinkRepo.createPasswordResetRequest).not.toHaveBeenCalled();
    expect(notificationPort.sendMagicLink).not.toHaveBeenCalled();
  });

  it('returns error when rate limit exceeded', async () => {
    magicLinkRepo.checkRateLimit.mockResolvedValue(
      Result.err({ code: 'RATE_LIMIT_EXCEEDED', details: { message: 'Rate limit exceeded' } })
    );

    const result = await useCase.execute({ email: 'test@example.com' });

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr().code).toBe('RATE_LIMIT_EXCEEDED');
  });

  it('returns error when repository call fails', async () => {
    authRepo.findByEmail.mockRejectedValue(new Error('Database error'));
    magicLinkRepo.checkRateLimit.mockResolvedValue(Result.ok(undefined));

    const result = await useCase.execute({ email: 'test@example.com' });

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