import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:recording_tool/app/config/api_common.dart';
import 'package:recording_tool/core/network/providers/dio_providers.dart';
import 'package:recording_tool/core/utils/device_utils.dart';
import 'package:recording_tool/features/auth/model/model_auth.dart';

class AuthServer {
  /// [passCode] 口令码
  static Future<GetTokenResModel> login(String passCode, Ref ref) async {
    final deviceCode = await DeviceUtils.deviceCode();
    if (deviceCode.isEmpty) {
      throw const FormatException('无法获取设备标识');
    }

    final apiClient = ref.read(apiClientProvider);
    final data = await apiClient.post<GetTokenResModel>(
      AuthApi.getToken.path,
      data: {'deviceCode': deviceCode, 'passCode': passCode},
      parser: (json) => GetTokenResModel.fromJson(json as Map<String, dynamic>),
    );

    if (data.deviceAccessToken.isEmpty) {
      throw const FormatException('登录响应缺少 TOKEN');
    }

    return data;
  }

  /// 获取赛事列表
  /// [path] 赛事目录
  static Future<GetRecordListResModel> getRecordList(
    Ref ref,
    String path,
  ) async {
    final apiClient = ref.read(apiClientProvider);
    final data = await apiClient.get<GetRecordListResModel>(
      'http://sheling.local:9001/${AuthApi.getRecordList.path}',
      queryParameters: {'path': path},
      parser: (json) =>
          GetRecordListResModel.fromJson(json as Map<String, dynamic>),
    );
    return data;
  }
}
