import 'package:flutter/foundation.dart';
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';
import 'package:recording_tool/features/auth/model/model_jwt.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] 赛事目录
  /// [nasIpAddr] NAS IP，由调用方传入，避免在 authProvider 内部再 read(authProvider)。
  static Future<GetRecordListResModel?> getRecordList(
    Ref ref, {
    required String path,
    required String nasIpAddr,
  }) async {
    try {
      if (nasIpAddr.isEmpty) {
        throw const FormatException('无法获取NAS IP地址');
      }
      final apiClient = ref.read(apiClientProvider);
      // NAS /api/files 直接返回 {path, items}，不是业务网关的 {code,message,data} 包装。
      final data = await apiClient.get<GetRecordListResModel>(
        'http://$nasIpAddr:9001/${AuthApi.getRecordList.path}',
        queryParameters: {'path': path},
        wrapResponse: false,
        parser: (json) {
          if (json is! Map) {
            throw const FormatException('录像列表响应格式错误');
          }
          return GetRecordListResModel.fromJson(
            Map<String, dynamic>.from(json),
          );
        },
      );
      return data;
    } catch (error) {
      debugPrint('getRecordList failed: $error');
      return null;
    }
  }

  /// 获取登录设备信息
  static Future<JwtDecodedData?> getLoginDeviceInfo(Ref ref) async {
    try {
      final apiClient = ref.read(apiClientProvider);
      final data = await apiClient.get<JwtDecodedData>(
        AuthApi.getLoginDeviceInfo.path,
        parser: (json) {
          if (json is! Map) {
            throw const FormatException('登录设备信息响应格式错误');
          }
          return JwtDecodedData.fromJson(Map<String, dynamic>.from(json));
        },
      );
      return data;
    } catch (error) {
      debugPrint('getLoginDeviceInfo failed: $error');
      return null;
    }
  }
}
