import 'package:dio/dio.dart';

import '../../models/history_event.dart';
import '../../models/quarantine_mine.dart';
import '../../models/system_playlists_status.dart';

/// /api/me/* endpoints — caller-scoped data (history, profile, etc.).
class MeApi {
  MeApi(this._dio);
  final Dio _dio;

  /// GET /api/me/history. Paginated via offset/limit; server emits
  /// `{events, has_more}` rather than the standard `Page<T>` envelope.
  Future<HistoryPage> history({int limit = 50, int offset = 0}) async {
    final r = await _dio.get<Map<String, dynamic>>(
      '/api/me/history',
      queryParameters: {'limit': limit, 'offset': offset},
    );
    return HistoryPage.fromJson(r.data ?? const {});
  }

  /// GET /api/quarantine/mine — flat list (no envelope).
  Future<List<QuarantineMineRow>> quarantineMine() async {
    final r = await _dio.get<List<dynamic>>('/api/quarantine/mine');
    final raw = r.data ?? const [];
    return raw
        .map((e) =>
            QuarantineMineRow.fromJson((e as Map).cast<String, dynamic>()))
        .toList(growable: false);
  }

  /// GET /api/me/system-playlists-status. Returns the caller's most
  /// recent system-playlist build state. Used by the home Playlists
  /// row to choose between real and placeholder cards.
  Future<SystemPlaylistsStatus> systemPlaylistsStatus() async {
    final r = await _dio.get<Map<String, dynamic>>(
      '/api/me/system-playlists-status',
    );
    return SystemPlaylistsStatus.fromJson(r.data ?? const {});
  }

  /// PUT /api/me/timezone — submit the device's IANA timezone. The
  /// scheduler uses this to fire the user's daily playlist build at
  /// 03:00 in their local time. See AuthController._sendTimezoneIfStale
  /// for the weekly cadence trigger.
  Future<void> putTimezone(String timezone) async {
    await _dio.put<void>('/api/me/timezone', data: {'timezone': timezone});
  }
}
