import '../../contracts/contracts.dart';
import '../errors.dart';
import '../ports/emby_gateway.dart';
import '../ports/server_repository.dart';
import '../ports/session_repository.dart';


Future<AuthedRequestContext> resolveAuthedContext({
  required SessionRepository sessionRepository,
  required ServerRepository serverRepository,
}) async {
  final session = await sessionRepository.getActive();
  if (session == null) {
    throw DomainError(ErrorCode.storeNotFound, '没有活跃会话');
  }
  final server = await serverRepository.findById(session.serverId);
  if (server == null) {
    throw DomainError(
      ErrorCode.storeNotFound,
      '服务器不存在',
      details: {'serverId': session.serverId},
    );
  }
  return AuthedRequestContext(
    baseUrl: server.baseUrl,
    token: session.token,
    userId: session.userId,
  );
}


Future<AuthedRequestContext?> resolveAuthedContextForServer({
  required SessionRepository sessionRepository,
  required ServerRepository serverRepository,
  required String serverId,
}) async {
  final session = await sessionRepository.getByServerId(serverId);
  if (session == null) return null;
  final server = await serverRepository.findById(serverId);
  if (server == null) return null;
  return AuthedRequestContext(
    baseUrl: server.baseUrl,
    token: session.token,
    userId: session.userId,
  );
}


abstract class AuthedUseCase {
  AuthedUseCase({
    required this.sessionRepository,
    required this.serverRepository,
    required this.embyGateway,
  });

  final SessionRepository sessionRepository;
  final ServerRepository serverRepository;
  final EmbyGateway embyGateway;


  Future<AuthedRequestContext> ctx() => resolveAuthedContext(
    sessionRepository: sessionRepository,
    serverRepository: serverRepository,
  );


  Future<AuthedRequestContext> requireCtxForServer(String serverId) async {
    final ctx = await resolveAuthedContextForServer(
      sessionRepository: sessionRepository,
      serverRepository: serverRepository,
      serverId: serverId,
    );
    if (ctx == null) {
      throw DomainError(
        ErrorCode.storeNotFound,
        '服务器无活跃会话',
        details: {'serverId': serverId},
      );
    }
    return ctx;
  }
}
