import 'package:flutter/foundation.dart';
import '../network/api_client.dart';

/// SMS 验证码类型
enum SmsCodeType {
  register('REGISTER'),
  login('LOGIN'),
  resetPassword('RESET_PASSWORD'),
  changePhone('CHANGE_PHONE');

  final String value;
  const SmsCodeType(this.value);
}

/// 认证服务
class AuthService {
  final ApiClient _apiClient;

  AuthService({ApiClient? apiClient})
      : _apiClient = apiClient ?? ApiClient.instance;

  /// 发送短信验证码 (支持类型)
  Future<int> sendSmsCode(String phone, {SmsCodeType type = SmsCodeType.login}) async {
    try {
      final response = await _apiClient.post('/api/v1/auth/sms/send', data: {
        'phone': phone,
        'type': type.value,
      });
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return (inner is Map<String, dynamic>) ? (inner['expiresIn'] as int?) ?? 300 : 300;
    } catch (e) {
      debugPrint('[AuthService] sendSmsCode 失败: $e');
      rethrow;
    }
  }

  /// 手机号+验证码登录
  Future<LoginResult> loginByPhone(String phone, String smsCode) async {
    try {
      final response = await _apiClient.post('/api/v1/auth/login-phone', data: {
        'phone': phone,
        'smsCode': smsCode,
      });
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return LoginResult.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[AuthService] loginByPhone 失败: $e');
      rethrow;
    }
  }

  /// 密码登录
  Future<LoginResult> loginByPassword(String identifier, String password) async {
    try {
      final response = await _apiClient.post('/api/v1/auth/login', data: {
        'identifier': identifier,
        'password': password,
      });
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return LoginResult.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[AuthService] loginByPassword 失败: $e');
      rethrow;
    }
  }

  /// 刷新 Token
  Future<LoginResult> refreshToken(String refreshToken) async {
    try {
      final response = await _apiClient.post('/api/v1/auth/refresh', data: {
        'refreshToken': refreshToken,
      });
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return LoginResult.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[AuthService] refreshToken 失败: $e');
      rethrow;
    }
  }

  /// 登出
  Future<void> logout() async {
    try {
      await _apiClient.post('/api/v1/auth/logout');
    } catch (e) {
      debugPrint('[AuthService] logout 失败: $e');
    }
  }
}

class LoginResult {
  final String accessToken;
  final String? refreshToken;
  final Map<String, dynamic>? user;

  const LoginResult({
    required this.accessToken,
    this.refreshToken,
    this.user,
  });

  factory LoginResult.fromJson(Map<String, dynamic> json) {
    // 后端返回 { user, tokens: { accessToken, refreshToken, expiresIn } }
    final tokens = json['tokens'] as Map<String, dynamic>?;
    if (tokens != null) {
      return LoginResult(
        accessToken: tokens['accessToken'] as String? ?? '',
        refreshToken: tokens['refreshToken'] as String?,
        user: json['user'] as Map<String, dynamic>?,
      );
    }
    // 兼容 refresh 等直接返回 tokens 的接口
    return LoginResult(
      accessToken: json['accessToken'] as String? ?? '',
      refreshToken: json['refreshToken'] as String?,
      user: json['user'] as Map<String, dynamic>?,
    );
  }
}
