import 'package:appwrite/appwrite.dart';
import 'package:appwrite/models.dart';
import 'package:bealbot_ai/core/core.dart';
import 'package:bealbot_ai/features/auth/data/appwrite_auth_state.dart';
import 'package:bealbot_ai/features/auth/domain/app_user.dart';
import 'package:flutter/foundation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
// Want to sign up or get user account -> Account (from appwrite)
// Want to access user related data -> model.User (from models.dart)
part 'auth_repository.g.dart';
@Riverpod(keepAlive: true)
Future<User?> authState(AuthStateRef ref) async {
return ref.watch(appwriteAuthStateProvider).value;
}
@Riverpod(keepAlive: true)
AuthRepository authRepository(AuthRepositoryRef ref) {
final account = ref.watch(appwriteAccountProvider);
return AuthRepository(account: account);
}
class AuthRepository {
AuthRepository({required this.account});
final Account account;
User? user;
User? get currentUser {
if (user != null) {
return user;
} else {
return null;
}
}
Future<User?> checkCurrentUser() async {
try {
final maybeUser = await account.get();
user = maybeUser;
} catch (e) {
return Future.value(null);
}
return null;
}
Future<AppUser> signUp({
required String email,
required String password,
}) async {
try {
final userId = ID.unique();
await account.create(
userId: userId,
email: email,
password: password,
);
final AppUser appUser = AppUser(
$id: userId,
email: email,
name: getNameFromEmail(email),
profilePic: '',
);
return appUser;
} on AppwriteException catch (e, st) {
//TODO: Implement Error Handling
debugPrint("Appwrite Exception: ${e.message}\n${st.toString()}");
} catch (e, st) {
//TODO: Implement Error Handling
debugPrint("Appwrite Exception: ${e.toString()}\n${st.toString()}");
}
throw Exception("Failed to sign up user, we should never reach here");
}
Future<void> login({
required String email,
required String password,
}) async {
try {
final result = await account.createEmailSession(
email: email,
password: password,
);
debugPrint(result.toString());
} on AppwriteException catch (e, st) {
//TODO: Implement Error Handling
debugPrint("Appwrite Exception: ${e.message}\n${st.toString()}");
} catch (e, st) {
//TODO: Implement Error Handling
debugPrint("Appwrite Exception: ${e.toString()}\n${st.toString()}");
}
}
}