import 'package:networks_sdk/networks_sdk.dart';

import 'package:im_app/domain/entities/user.dart';
import 'package:im_app/domain/repositories/auth_repository.dart';
import 'package:im_app/data/remote/login_request.dart';
import 'package:im_app/data/remote/logout_request.dart';
import 'package:im_app/data/remote/send_otp_request.dart';
import 'package:im_app/data/remote/verify_otp_request.dart';

/// 认证 Repository 实现
///
/// implements [AuthRepository] 接口（domain/repositories/ 中定义）。
/// 直接使用 [NetworksSdkApi] 发送请求，将 DTO 转为 Domain Entity。
///
/// ## 登录流程
///
/// ```
/// LoginUseCase.sendOtp(countryCode, contact)
///   → ★ AuthRepositoryImpl.sendOtp() ★         ← 你在这里（步骤 1）
///     → NetworksSdkApi.executeRequest(SendOtpRequest)
///       → 服务端 POST /app/api/auth/otp/send
///
/// LoginUseCase.verifyAndLogin(countryCode, contact, code)
///   → ★ AuthRepositoryImpl.verifyOtp() ★        ← 你在这里（步骤 2）
///     → NetworksSdkApi.executeRequest(VerifyOtpRequest)
///       → 服务端 POST /app/api/auth/vcode/check
///     ← VerifyOtpResponse.token = vcode_token
///   → ★ AuthRepositoryImpl.login() ★            ← 你在这里（步骤 3）
///     → NetworksSdkApi.executeRequest(LoginRequest)
///       → 服务端 POST /app/api/auth/login-user
///     ← LoginResponse → _onTokenUpdate(accessToken) → User
/// ```
class AuthRepositoryImpl implements AuthRepository {
  final NetworksSdkApi _client;
  final void Function(String?) _onTokenUpdate;

  AuthRepositoryImpl({
    required NetworksSdkApi client,
    required void Function(String?) onTokenUpdate,
  }) : _client = client,
       _onTokenUpdate = onTokenUpdate;

  @override
  Future<void> sendOtp({
    required String countryCode,
    required String contact,
  }) async {
    await _client.executeRequest(
      SendOtpRequest(countryCode: countryCode, contact: contact),
    );
  }

  @override
  Future<String> verifyOtp({
    required String countryCode,
    required String contact,
    required String code,
  }) async {
    final response = await _client.executeRequest(
      VerifyOtpRequest(
        countryCode: countryCode,
        contact: contact,
        code: code,
      ),
    );

    if (response == null) {
      throw Exception('Verify OTP failed: empty response');
    }

    return response.token;
  }

  @override
  Future<User> login({
    required String countryCode,
    required String contact,
    required String vcodeToken,
  }) async {
    final response = await _client.executeRequest(
      LoginRequest(
        countryCode: countryCode,
        contact: contact,
        vcodeToken: vcodeToken,
      ),
    );

    if (response == null) {
      throw Exception('Login failed: empty response');
    }

    _onTokenUpdate(response.accessToken);

    return response.toEntity();
  }

  @override
  Future<void> logout() async {
    await _client.executeRequest(LogoutRequest());
    _onTokenUpdate(null); // 清除 Token（内存 + 持久化由 Provider 层组合）
  }
}
