import '../utils/constants.dart';
import '../utils/http/response_model.dart';
import '../utils/http/dio_request.dart';
import '../models/bo/login_model.dart';
import '../models/bo/user_model.dart';
import 'mock/auth_mock_data.dart';

class AuthRepository {
  Future<ResponseModel<LoginModel>> login(
      String phone, String smsCode) {
    // if (Constants.useMockData) {
    //   return _mockLogin();
    // }
    return DioRequest.instance.post<LoginModel>(
      '/merchant/account/sms-login',
      data: {'phone': phone, 'smsCode': smsCode},
      fromJsonT: (data) => LoginModel.fromJson(data as Map<String, dynamic>),
    );
  }

  Future<ResponseModel<UserModel>> getUserInfo() {
    if (Constants.useMockData) {
      return _mockGetUserInfo();
    }
    return DioRequest.instance.get<UserModel>(
      '/app/auth/user-info',
      fromJsonT: (data) => UserModel.fromJson(data as Map<String, dynamic>),
    );
  }

  Future<ResponseModel> logout() {
    if (Constants.useMockData) {
      return _mockLogout();
    }
    return DioRequest.instance.post('/app/auth/logout');
  }

  // ==================== Mock 实现 ====================

  Future<ResponseModel<LoginModel>> _mockLogin() async {
    // 模拟网络延迟，便于测试 loading 状态
    await Future.delayed(const Duration(milliseconds: 500));

    final loginModel = AuthMockData.mockLogin();
    return ResponseModel<LoginModel>(
      code: 200,
      msg: '登录成功（mock）',
      data: loginModel,
      uuid: 'mock_uuid_${DateTime.now().millisecondsSinceEpoch}',
      success: true,
      timestamp: DateTime.now().millisecondsSinceEpoch,
    );
  }

  Future<ResponseModel<UserModel>> _mockGetUserInfo() async {
    await Future.delayed(const Duration(milliseconds: 300));

    final userInfo = AuthMockData.mockUserInfo();
    return ResponseModel<UserModel>(
      code: 200,
      msg: '获取用户信息成功（mock）',
      data: userInfo,
      uuid: 'mock_uuid_${DateTime.now().millisecondsSinceEpoch}',
      success: true,
      timestamp: DateTime.now().millisecondsSinceEpoch,
    );
  }

  Future<ResponseModel> _mockLogout() async {
    await Future.delayed(const Duration(milliseconds: 200));

    return ResponseModel(
      code: 200,
      msg: '退出成功（mock）',
      uuid: 'mock_uuid_${DateTime.now().millisecondsSinceEpoch}',
      success: true,
      timestamp: DateTime.now().millisecondsSinceEpoch,
    );
  }
}
