import 'package:dio/dio.dart';
import '../../../../core/network/api_endpoints.dart';
import '../models/user_model.dart';

class AuthRemoteDatasource {
  final Dio _dio;

  AuthRemoteDatasource(this._dio);

  /// POST /api/login → { token, user }
  Future<({String token, UserModel user})> login(
      String email, String password) async {
    final response = await _dio.post(
      ApiEndpoints.login,
      data: {'email': email, 'password': password},
    );
    final data = response.data as Map<String, dynamic>;
    return (
      token: data['token'] as String,
      user: UserModel.fromJson(data['user'] as Map<String, dynamic>),
    );
  }

  /// POST /api/register → { token, user }
  Future<({String token, UserModel user})> register(
      String username, String email, String password) async {
    final response = await _dio.post(
      ApiEndpoints.register,
      data: {'username': username, 'email': email, 'password': password},
    );
    final data = response.data as Map<String, dynamic>;
    return (
      token: data['token'] as String,
      user: UserModel.fromJson(data['user'] as Map<String, dynamic>),
    );
  }

  /// GET /api/me → { user }
  Future<UserModel> getMe() async {
    final response = await _dio.get(ApiEndpoints.me);
    final data = response.data as Map<String, dynamic>;
    return UserModel.fromJson(data['user'] as Map<String, dynamic>);
  }

  /// POST /api/logout
  Future<void> logout() async {
    try {
      await _dio.post(ApiEndpoints.logout);
    } catch (_) {
      // Ignore logout errors — we clear local token regardless
    }
  }
}