import type { AsyncUseCase } from '@core/shared/application';
import type { Logger } from '@core/shared/application';
import type { ISocialGraphRepository } from '../../domain/repositories/ISocialGraphRepository';
import type { CurrentUserSocialDTO } from '../dto/CurrentUserSocialDTO';
import type { FriendDTO } from '../dto/FriendDTO';
import type {
  CurrentUserSocialViewModel,
  ICurrentUserSocialPresenter,
} from '../presenters/ISocialPresenters';

export interface GetCurrentUserSocialParams {
  driverId: string;
}

/**
 * Application-level use case to retrieve the current user's social context.
 *
 * Keeps orchestration in the social bounded context while delegating
 * data access to domain repositories and presenting via a presenter.
 */
export class GetCurrentUserSocialUseCase
  implements AsyncUseCase<GetCurrentUserSocialParams, void> {
  constructor(
    private readonly socialGraphRepository: ISocialGraphRepository,
    public readonly presenter: ICurrentUserSocialPresenter,
    private readonly logger: Logger,
  ) {}

  async execute(params: GetCurrentUserSocialParams): Promise<void> {
    this.logger.debug('GetCurrentUserSocialUseCase: Starting execution', { params });
    try {
      const { driverId } = params;

      this.logger.debug(`GetCurrentUserSocialUseCase: Fetching friends for driverId: ${driverId}`);
      const friendsDomain = await this.socialGraphRepository.getFriends(driverId);
      this.logger.debug('GetCurrentUserSocialUseCase: Successfully fetched friends from social graph repository', { friendsCount: friendsDomain.length });
      if (friendsDomain.length === 0) {
        this.logger.warn(`GetCurrentUserSocialUseCase: No friends found for driverId: ${driverId}`);
      }

      const friends: FriendDTO[] = friendsDomain.map((friend) => ({
        driverId: friend.id,
        displayName: friend.name,
        avatarUrl: '',
        isOnline: false,
        lastSeen: new Date(),
      }));

      const currentUser: CurrentUserSocialDTO = {
        driverId,
        displayName: '',
        avatarUrl: '',
        countryCode: '',
      };

      const viewModel: CurrentUserSocialViewModel = {
        currentUser,
        friends,
      };

      this.presenter.present(viewModel);
      this.logger.info('GetCurrentUserSocialUseCase: Successfully presented current user social data');
    } catch (error) {
      this.logger.error('GetCurrentUserSocialUseCase: Error during execution', { error });
      throw error;
    }
  }
}