import '../domain/domain.dart';
import 'ports.dart';

const _minimumPasswordLength = 8;
final _emailPattern = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$');

final class RegisterUserUseCase {
  const RegisterUserUseCase({
    required this.users,
    required this.passwordHasher,
    required this.clock,
    required this.ids,
  });

  final UserRepository users;
  final PasswordHasher passwordHasher;
  final Clock clock;
  final IdGenerator ids;

  Future<UserAccount> execute({
    required String email,
    required String password,
    String? displayName,
  }) async {
    final normalizedEmail = _validateEmail(email);
    _validatePassword(password);

    final existing = await users.findByEmail(normalizedEmail);
    if (existing != null) {
      throw const EmailAlreadyTakenException();
    }

    final now = clock.now().toUtc();
    final user = UserAccount(
      id: ids.newId(),
      email: normalizedEmail,
      passwordHash: await passwordHasher.hash(password),
      displayName: _blankToNull(displayName),
      createdAt: now,
      updatedAt: now,
    );
    await users.insert(user);
    return user;
  }
}

final class LoginResult {
  const LoginResult({
    required this.user,
    required this.session,
    required this.token,
  });

  final UserAccount user;
  final AuthSession session;
  final String token;

  DateTime get expiresAt => session.expiresAt;
}

final class LoginUseCase {
  const LoginUseCase({
    required this.users,
    required this.sessions,
    required this.passwordHasher,
    required this.tokens,
    required this.clock,
    required this.ids,
    this.sessionDuration = const Duration(days: 30),
  });

  final UserRepository users;
  final AuthSessionRepository sessions;
  final PasswordHasher passwordHasher;
  final OpaqueTokenService tokens;
  final Clock clock;
  final IdGenerator ids;
  final Duration sessionDuration;

  Future<LoginResult> execute({
    required String email,
    required String password,
    String? userAgent,
    String? deviceLabel,
  }) async {
    final normalizedEmail = _validateEmail(email);
    final user = await users.findByEmail(normalizedEmail);
    if (user == null || user.isDisabled) {
      throw const InvalidCredentialsException();
    }
    final verified = await passwordHasher.verify(
      password: password,
      passwordHash: user.passwordHash,
    );
    if (!verified) {
      throw const InvalidCredentialsException();
    }

    final now = clock.now().toUtc();
    final token = tokens.generateToken();
    final session = AuthSession(
      id: ids.newId(),
      userId: user.id,
      tokenHash: tokens.hashToken(token),
      issuedAt: now,
      expiresAt: now.add(sessionDuration),
      userAgent: _blankToNull(userAgent),
      deviceLabel: _blankToNull(deviceLabel),
    );
    await sessions.insert(session);
    return LoginResult(user: user, session: session, token: token);
  }
}

final class LogoutUseCase {
  const LogoutUseCase({
    required this.sessions,
    required this.tokens,
    required this.clock,
  });

  final AuthSessionRepository sessions;
  final OpaqueTokenService tokens;
  final Clock clock;

  Future<void> execute({required String token}) async {
    final session = await sessions.findByTokenHash(tokens.hashToken(token));
    if (session == null || !session.isActiveAt(clock.now())) {
      throw const UnauthorizedException();
    }
    await sessions.revoke(
      sessionId: session.id,
      revokedAt: clock.now().toUtc(),
    );
  }
}

final class AuthenticatedRequest {
  const AuthenticatedRequest({required this.user, required this.session});

  final UserAccount user;
  final AuthSession session;
}

final class AuthenticateRequestUseCase {
  const AuthenticateRequestUseCase({
    required this.users,
    required this.sessions,
    required this.tokens,
    required this.clock,
  });

  final UserRepository users;
  final AuthSessionRepository sessions;
  final OpaqueTokenService tokens;
  final Clock clock;

  Future<AuthenticatedRequest> execute({required String token}) async {
    final session = await sessions.findByTokenHash(tokens.hashToken(token));
    if (session == null || !session.isActiveAt(clock.now())) {
      throw const UnauthorizedException();
    }
    final user = await users.findById(session.userId);
    if (user == null || user.isDisabled) {
      throw const UnauthorizedException();
    }
    return AuthenticatedRequest(user: user, session: session);
  }
}

String _validateEmail(String email) {
  final normalized = email.trim().toLowerCase();
  if (!_emailPattern.hasMatch(normalized)) {
    throw const ValidationException('Email format is invalid.');
  }
  return normalized;
}

void _validatePassword(String password) {
  if (password.length < _minimumPasswordLength) {
    throw const ValidationException(
      'Password must contain at least 8 characters.',
    );
  }
}

String? _blankToNull(String? value) {
  final trimmed = value?.trim();
  return trimmed == null || trimmed.isEmpty ? null : trimmed;
}
