import 'package:dio/dio.dart';

import '../../models/admin_user.dart';

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

  /// GET /api/admin/users → `{"users": [...]}`. Envelope unwrapped here.
  Future<List<AdminUser>> list() async {
    final r = await _dio.get<Map<String, dynamic>>('/api/admin/users');
    final raw = (r.data?['users'] as List?) ?? const [];
    return raw
        .map((e) => AdminUser.fromJson((e as Map).cast<String, dynamic>()))
        .toList(growable: false);
  }

  Future<void> setAdmin(String id, bool isAdmin) async {
    await _dio.put<void>(
      '/api/admin/users/$id/admin',
      data: {'is_admin': isAdmin},
    );
  }

  /// Server's body field is `auto_approve` (NOT `auto_approve_requests`)
  /// — different from the response field name. Verified against
  /// internal/api/admin_users.go `adminAutoApproveReq` (May 2026).
  Future<void> setAutoApprove(String id, bool autoApprove) async {
    await _dio.put<void>(
      '/api/admin/users/$id/auto-approve',
      data: {'auto_approve': autoApprove},
    );
  }

  /// Admin supplies the new password; server returns 204. There is no
  /// server-generated-password mode.
  Future<void> resetPassword(String id, String newPassword) async {
    await _dio.post<void>(
      '/api/admin/users/$id/reset-password',
      data: {'password': newPassword},
    );
  }

  Future<void> delete(String id) async {
    await _dio.delete<void>('/api/admin/users/$id');
  }
}
