import 'package:uuid/uuid.dart';
import 'package:barber_app/core/database/database_service.dart';
import 'package:barber_app/core/utils/password_utils.dart';
import 'package:barber_app/features/auth/data/models/user_model.dart';
import 'package:barber_app/features/settings/data/models/settings_model.dart';

class AuthRepository {
  final _uuid = const Uuid();

  // Registrar novo usuário
  Future<UserModel?> register({
    required String email,
    required String password,
    required String barberName,
    required String barberShopName,
  }) async {
    try {
      // Verifica se email já existe
      final existingUser = DatabaseService.usersBoxInstance.values
          .where((user) => user.email.toLowerCase() == email.toLowerCase())
          .firstOrNull;

      if (existingUser != null) {
        throw Exception('E-mail já cadastrado');
      }

      final userId = _uuid.v4();
      final user = UserModel(
        id: userId,
        email: email.toLowerCase().trim(),
        passwordHash: PasswordUtils.hashPassword(password),
        barberName: barberName.trim(),
        barberShopName: barberShopName.trim(),
        createdAt: DateTime.now(),
      );

      await DatabaseService.usersBoxInstance.put(userId, user);

      // Cria configurações padrão
      final settings = SettingsModel(userId: userId);
      await DatabaseService.settingsBoxInstance.put(userId, settings);

      // Define como usuário atual
      await DatabaseService.setCurrentUserId(userId);

      return user;
    } catch (e) {
      rethrow;
    }
  }

  // Login
  Future<UserModel?> login({
    required String email,
    required String password,
  }) async {
    try {
      final user = DatabaseService.usersBoxInstance.values
          .where((u) => u.email.toLowerCase() == email.toLowerCase().trim())
          .firstOrNull;

      if (user == null) {
        throw Exception('Usuário não encontrado');
      }

      if (!PasswordUtils.verifyPassword(password, user.passwordHash)) {
        throw Exception('Senha incorreta');
      }

      await DatabaseService.setCurrentUserId(user.id);
      return user;
    } catch (e) {
      rethrow;
    }
  }

  // Logout
  Future<void> logout() async {
    await DatabaseService.setCurrentUserId(null);
  }

  // Obter usuário atual
  UserModel? getCurrentUser() {
    final userId = DatabaseService.getCurrentUserId();
    if (userId == null) return null;
    return DatabaseService.usersBoxInstance.get(userId);
  }

  // Verificar se está logado
  bool isLoggedIn() {
    return DatabaseService.isLoggedIn();
  }

  // Atualizar perfil
  Future<UserModel?> updateProfile({
    required String barberName,
    required String barberShopName,
  }) async {
    final currentUser = getCurrentUser();
    if (currentUser == null) return null;

    final updatedUser = currentUser.copyWith(
      barberName: barberName.trim(),
      barberShopName: barberShopName.trim(),
    );

    await DatabaseService.usersBoxInstance.put(currentUser.id, updatedUser);
    return updatedUser;
  }

  // Alterar senha
  Future<bool> changePassword({
    required String currentPassword,
    required String newPassword,
  }) async {
    final currentUser = getCurrentUser();
    if (currentUser == null) return false;

    if (!PasswordUtils.verifyPassword(currentPassword, currentUser.passwordHash)) {
      throw Exception('Senha atual incorreta');
    }

    final updatedUser = currentUser.copyWith(
      passwordHash: PasswordUtils.hashPassword(newPassword),
    );

    await DatabaseService.usersBoxInstance.put(currentUser.id, updatedUser);
    return true;
  }
}
