import 'package:dartz/dartz.dart';
import '../../../data/models/auth/token_response.dart';
import '../../../data/models/auth/refresh_token_request.dart';
import '../../repositories/auth_repository.dart';
import '../../../core/errors/failures.dart';
import '../base_usecase.dart';

/// 토큰 갱신 UseCase
/// JWT 토큰을 갱신하여 세션 유지
class RefreshTokenUseCase extends UseCase<TokenResponse, NoParams> {
  // AuthRepository 기반으로 마이그레이션
  final AuthRepository _authRepository;

  RefreshTokenUseCase(this._authRepository);

  @override
  Future<Either<Failure, TokenResponse>> call(NoParams params) async {
    final stored = await _authRepository.getStoredRefreshToken();
    return await stored.fold(
      (failure) => Left(failure),
      (token) async {
        if (token == null || token.isEmpty) {
          return Left(AuthFailure(
            message: '갱신 토큰이 없습니다. 다시 로그인해주세요.',
            code: 'NO_REFRESH_TOKEN',
          ));
        }
        final request = RefreshTokenRequest(refreshToken: token);
        return await _authRepository.refreshToken(request);
      },
    );
  }
}
