import '../models/user.dart';
import '../repositories/auth_repository.dart';
import '../services/api_client.dart';

class HttpAuthRepository implements AuthRepository {
  final ApiClient _apiClient;
  HttpAuthRepository(this._apiClient);

  @override
  Future<User> login(String email, String password) async {
    final res = await _apiClient.post(
      '/auth/password-login',
      data: {'username': email, 'password': password},
      fromJson: (d) {
        final user = d['user'];
        return User(
          id: user['id'].toString(),
          username: user['username'] ?? user['email'],
          email: user['email'],
          createdAt: DateTime.parse(
            user['createdAt'] ?? DateTime.now().toIso8601String(),
          ),
        );
      },
    );
    return res;
  }

  @override
  Future<User?> getCurrentUser() async {
    // No refresh endpoint available - rely on SessionBloc for token management
    // If token is stored and valid, SessionBloc will restore it
    // If API calls return 401, session will expire automatically
    return null;
  }

  @override
  Future<void> logout() async {
    try {
      // Call backend to revoke session
      await _apiClient.post('/auth/logout', fromJson: (d) => null);
    } catch (_) {
      // Ignore logout errors - clear local session regardless
    }
  }
}
