import 'package:demo/app_error.dart';
import 'package:fpdart/fpdart.dart';

// Mock-Datenbank
final existingEmails = ["existing@example.com"];

// Validierungsfunktionen
Either<AppError, String> validateName(String name) {
  return name.isNotEmpty
      ? Either.right(name)
      : AppError.left(
          "Name cannot be empty",
          type: AppErrorType.ValidationError,
        );
}

Either<AppError, String> validateEmail(String email) {
  final emailRegex = RegExp(r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+");
  return emailRegex.hasMatch(email)
      ? Either.right(email)
      : AppError.left(
          "Invalid email format",
          type: AppErrorType.ValidationError,
        );
}

// Asynchrone Überprüfung, ob die E-Mail bereits existiert
TaskEither<AppError, bool> checkEmailExists(String email) {
  return TaskEither.tryCatch(
    () async => existingEmails.contains(email),
    (error, _) => AppError(
      message: "Error checking email existence",
      type: AppErrorType.DatabaseError,
      exception: error as Exception?,
    ),
  );
}

// Benutzer in der Datenbank speichern (Dummy-Implementierung)
TaskEither<AppError, bool> saveUser(String name, String email) {
  return TaskEither.tryCatch(
    () async {
      await Future.delayed(Duration(seconds: 1)); // Simulierte Latenz
      print("User saved: $name, $email");
      return true;
    },
    (error, _) => AppError(
      message: "Error saving user",
      type: AppErrorType.DatabaseError,
      exception: error as Exception?,
    ),
  );
}

// Optional: Begrüßungsnachricht senden
TaskEither<AppError, bool> sendWelcomeEmail(String email) {
  return TaskEither.tryCatch(
    () async {
      print("Welcome email sent to $email");
      return true;
    },
    (error, _) => AppError(
      message: "Error sending welcome email",
      type: AppErrorType.NetworkError,
      exception: error as Exception?,
    ),
  );
}
