import 'package:dio/dio.dart';

import '../../models/my_profile.dart';

class SettingsApi {
  SettingsApi(this._dio);
  final Dio _dio;

  Future<MyProfile> getProfile() async {
    final r = await _dio.get<Map<String, dynamic>>('/api/me');
    return MyProfile.fromJson(r.data ?? const {});
  }

  /// Pass only the fields you want to change; server merges. Empty
  /// strings clear; null leaves the existing value alone.
  Future<MyProfile> updateProfile({String? displayName, String? email}) async {
    final body = <String, dynamic>{};
    if (displayName != null) body['display_name'] = displayName;
    if (email != null) body['email'] = email;
    final r = await _dio.put<Map<String, dynamic>>(
      '/api/me/profile',
      data: body,
    );
    return MyProfile.fromJson(r.data ?? const {});
  }

  Future<void> changePassword({
    required String current,
    required String next,
  }) async {
    await _dio.put<void>('/api/me/password', data: {
      'current_password': current,
      'new_password': next,
    });
  }

  Future<ListenBrainzStatus> getListenBrainz() async {
    final r = await _dio.get<Map<String, dynamic>>('/api/me/listenbrainz');
    return ListenBrainzStatus.fromJson(r.data ?? const {});
  }

  Future<ListenBrainzStatus> setListenBrainzToken(String token) async {
    final r = await _dio.put<Map<String, dynamic>>(
      '/api/me/listenbrainz',
      data: {'token': token},
    );
    return ListenBrainzStatus.fromJson(r.data ?? const {});
  }

  Future<ListenBrainzStatus> setListenBrainzEnabled(bool enabled) async {
    final r = await _dio.put<Map<String, dynamic>>(
      '/api/me/listenbrainz',
      data: {'enabled': enabled},
    );
    return ListenBrainzStatus.fromJson(r.data ?? const {});
  }
}
