import 'package:dio/dio.dart';
import '../../../../core/config/api_endpoints.dart';
import '../../../../core/config/app_config.dart';
import '../models/auth_response.dart';

/// Remote datasource for authentication API calls.
/// Uses a standalone Dio instance (not the main one with token interceptor)
/// to avoid circular dependency during login/refresh.
class AuthRemoteDatasource {
  final AppConfig _config;

  AuthRemoteDatasource(this._config);

  Dio get _dio => Dio(BaseOptions(
        baseUrl: _config.apiBaseUrl,
        connectTimeout: const Duration(seconds: 10),
        receiveTimeout: const Duration(seconds: 15),
        headers: {'Content-Type': 'application/json'},
      ));

  /// Logs in with email and password.
  Future<AuthResponse> login({
    required String email,
    required String password,
  }) async {
    final response = await _dio.post(
      ApiEndpoints.login,
      data: {'email': email, 'password': password},
    );
    return AuthResponse.fromJson(response.data as Map<String, dynamic>);
  }

  /// Refreshes the access token using a refresh token.
  Future<Map<String, dynamic>> refreshToken(String refreshToken) async {
    final response = await _dio.post(
      ApiEndpoints.refreshToken,
      data: {'refreshToken': refreshToken},
    );
    return response.data as Map<String, dynamic>;
  }

  /// Fetches the current user profile using a provided access token.
  Future<AuthUser> getProfile(String accessToken) async {
    final dio = _dio;
    dio.options.headers['Authorization'] = 'Bearer $accessToken';
    final response = await dio.get(ApiEndpoints.profile);
    return AuthUser.fromJson(response.data as Map<String, dynamic>);
  }
}
