// ============================================================
// AuthRepositoryImpl — 认证仓库实现（数据层）
//
// 采用 Strangler Fig 模式：委托给现有的 AuthService 单例，
// 确保 ApiClient token 刷新/过期回调逻辑不重复实现。
// ============================================================

import '../../domain/entities/auth_user.dart';
import '../../domain/entities/auth_session.dart';
import '../../domain/repositories/auth_repository.dart';
import '../../../../core/services/auth_service.dart';

class AuthRepositoryImpl implements IAuthRepository {
  final AuthService _service;

  AuthRepositoryImpl({AuthService? service}) : _service = service ?? AuthService.instance;

  // ── 辅助：AuthResult → AuthSession ─────────────────────────

  AuthSession _toSession(AuthResult result) {
    return AuthSession(
      user: AuthUser.fromJson(result.user),
      accessToken: result.accessToken,
      refreshToken: result.refreshToken,
      expiresIn: result.expiresIn,
    );
  }

  // ── 会话恢复 ────────────────────────────────────────────────

  @override
  Future<AuthSession?> restoreSession() async {
    final restored = await _service.restoreSession();
    if (!restored) return null;
    final result = _service.authState.value;
    if (result == null) return null;
    return _toSession(result);
  }

  // ── 密码登录 ─────────────────────────────────────────────────

  @override
  Future<AuthSession> loginByPassword({
    required String identifier,
    required String password,
    String? deviceInfo,
  }) async {
    final result = await _service.loginByPassword(
      identifier: identifier,
      password: password,
      deviceInfo: deviceInfo,
    );
    return _toSession(result);
  }

  // ── SMS 验证码登录 ────────────────────────────────────────────

  @override
  Future<AuthSession> loginByPhone({
    required String phone,
    required String smsCode,
    String? deviceInfo,
  }) async {
    final result = await _service.loginByPhone(
      phone: phone,
      smsCode: smsCode,
      deviceInfo: deviceInfo,
    );
    return _toSession(result);
  }

  // ── 邮件验证码登录 ────────────────────────────────────────────

  @override
  Future<AuthSession> loginByEmail({
    required String email,
    required String emailCode,
    String? deviceInfo,
  }) async {
    final result = await _service.loginByEmail(email: email, emailCode: emailCode);
    return _toSession(result);
  }

  // ── 微信登录 ──────────────────────────────────────────────────

  @override
  Future<AuthSession> loginByWechat({
    required String code,
    String? referralCode,
    String? deviceInfo,
  }) async {
    final result = await _service.loginByWechat(
      code: code,
      referralCode: referralCode,
      deviceInfo: deviceInfo,
    );
    return _toSession(result);
  }

  // ── 支付宝登录 ────────────────────────────────────────────────

  @override
  Future<AuthSession> loginByAlipay({
    required String authCode,
    String? referralCode,
    String? deviceInfo,
  }) async {
    final result = await _service.loginByAlipay(
      authCode: authCode,
      referralCode: referralCode,
      deviceInfo: deviceInfo,
    );
    return _toSession(result);
  }

  // ── Google 登录 ────────────────────────────────────────────────

  @override
  Future<AuthSession> loginByGoogle({
    required String idToken,
    String? referralCode,
    String? deviceInfo,
  }) async {
    final result = await _service.loginByGoogle(
      idToken: idToken,
      referralCode: referralCode,
      deviceInfo: deviceInfo,
    );
    return _toSession(result);
  }

  // ── Apple 登录 ────────────────────────────────────────────────

  @override
  Future<AuthSession> loginByApple({
    required String identityToken,
    String? displayName,
    String? referralCode,
    String? deviceInfo,
  }) async {
    final result = await _service.loginByApple(
      identityToken: identityToken,
      displayName: displayName,
      referralCode: referralCode,
      deviceInfo: deviceInfo,
    );
    return _toSession(result);
  }

  // ── 注册 ──────────────────────────────────────────────────────

  @override
  Future<AuthSession> register({
    required String phone,
    required String smsCode,
    required String password,
    String? nickname,
    String? referralCode,
  }) async {
    final result = await _service.register(
      phone: phone,
      smsCode: smsCode,
      password: password,
      nickname: nickname,
      referralCode: referralCode,
    );
    return _toSession(result);
  }

  @override
  Future<AuthSession> registerByEmail({
    required String email,
    required String emailCode,
    required String password,
    String? nickname,
    String? referralCode,
  }) async {
    final result = await _service.registerByEmail(
      email: email,
      emailCode: emailCode,
      password: password,
      nickname: nickname,
      referralCode: referralCode,
    );
    return _toSession(result);
  }

  // ── 登出 ──────────────────────────────────────────────────────

  @override
  Future<void> logout() => _service.logout();

  // ── 验证码 ────────────────────────────────────────────────────

  @override
  Future<int> sendSmsCode(String phone, SmsCodeType type) =>
      _service.sendSmsCode(phone, type);

  @override
  Future<int> sendEmailCode(String email, EmailCodeType type) =>
      _service.sendEmailCode(email, type);

  // ── 密码管理 ─────────────────────────────────────────────────

  @override
  Future<void> resetPassword({
    required String phone,
    required String smsCode,
    required String newPassword,
  }) =>
      _service.resetPassword(phone: phone, smsCode: smsCode, newPassword: newPassword);

  @override
  Future<void> resetPasswordByEmail({
    required String email,
    required String emailCode,
    required String newPassword,
  }) =>
      _service.resetPasswordByEmail(
          email: email, emailCode: emailCode, newPassword: newPassword);

  @override
  Future<void> changePassword({
    required String oldPassword,
    required String newPassword,
  }) =>
      _service.changePassword(oldPassword: oldPassword, newPassword: newPassword);

  @override
  Future<void> changePhone({required String newPhone, required String newSmsCode}) =>
      _service.changePhone(newPhone: newPhone, newSmsCode: newSmsCode);

  // ── 支付宝工具 ────────────────────────────────────────────────

  @override
  Future<String> getAlipayAuthString() => _service.getAlipayAuthString();

  // ── 推荐码 ────────────────────────────────────────────────────

  @override
  Future<bool> validateReferralCode(String code) =>
      _service.validateReferralCode(code);
}
