import '../../../../core/errors/errors.dart';
import '../../../../core/network/api_client.dart';
import '../../../../core/errors/result.dart';
import '../../domain/entities/user.dart';
import '../models/auth_response.dart';
import 'auth_remote_datasource.dart';

class AuthRemoteDataSourceImpl implements AuthRemoteDataSource {
  final ApiClient apiClient;

  AuthRemoteDataSourceImpl(this.apiClient);

  @override
  Future<Result<AuthResponse>> login(String username, String password) async {
    final result = await apiClient.post<Map<String, dynamic>>(
      '/api/auth/login',
      data: {
        'username': username,
        'password': password,
      },
    );

    return result.fold(
      (error) => Result.failure(error),
      (data) {
        try {
          return Result.success(AuthResponse.fromJson(data));
        } catch (e) {
          return Result.failure(AppError.parsing(message: 'Invalid server response format: $e'));
        }
      },
    );
  }

  @override
  Future<Result<AuthResponse>> register(String username, String password, String name) async {
    final result = await apiClient.post<Map<String, dynamic>>(
      '/api/auth/register',
      data: {
        'username': username,
        'password': password,
        'displayName': name,
      },
    );

    return result.fold(
      (error) => Result.failure(error),
      (data) {
        try {
          return Result.success(AuthResponse.fromJson(data));
        } catch (e) {
          return Result.failure(AppError.parsing(message: 'Invalid server response format: $e'));
        }
      },
    );
  }

  @override
  Future<Result<void>> logout() async {
    return await apiClient.post('/api/auth/logout');
  }

  @override
  Future<Result<User>> getCurrentUser() async {
    final result = await apiClient.get<Map<String, dynamic>>('/api/auth/me');
    return result.fold(
      (error) => Result.failure(error),
      (data) {
        try {
          return Result.success(User(
            id: data['userId'] as String,
            email: data['username'] as String,
            name: data['displayName'] as String,
            avatarUrl: data['avatar'] as String?,
          ));
        } catch (e) {
          return Result.failure(AppError.parsing(message: 'Invalid user data format: $e'));
        }
      },
    );
  }

  @override
  Future<Result<void>> refreshToken() async {
    return await apiClient.post('/api/auth/refresh');
  }
}
