import type { AsyncUseCase } from '@core/shared/application';
import type { IFeedRepository } from '../../domain/repositories/IFeedRepository';
import type { FeedItemDTO } from '../dto/FeedItemDTO';
import type { FeedItem } from '../../domain/types/FeedItem';
import type {
  IUserFeedPresenter,
  UserFeedViewModel,
} from '../presenters/ISocialPresenters';
import type { Logger } from '@core/shared/application';

export interface GetUserFeedParams {
  driverId: string;
  limit?: number;
}

export class GetUserFeedUseCase
  implements AsyncUseCase<GetUserFeedParams, void> {
  constructor(
    private readonly feedRepository: IFeedRepository,
    public readonly presenter: IUserFeedPresenter,
    private readonly logger: Logger,
  ) {}

  async execute(params: GetUserFeedParams): Promise<void> {
    const { driverId, limit } = params;
    this.logger.debug('Executing GetUserFeedUseCase', { driverId, limit });

    try {
      const items = await this.feedRepository.getFeedForDriver(driverId, limit);
      this.logger.info('Successfully retrieved user feed', { driverId, itemCount: items.length });
      if (items.length === 0) {
        this.logger.warn(`No feed items found for driverId: ${driverId}`);
      }
      const dtoItems = items.map(mapFeedItemToDTO);

      const viewModel: UserFeedViewModel = {
        items: dtoItems,
      };

      this.presenter.present(viewModel);
    } catch (error) {
      this.logger.error('Failed to retrieve user feed', error);
      throw error; // Re-throw the error so it can be handled upstream
    }
  }
}

function mapFeedItemToDTO(item: FeedItem): FeedItemDTO {
  const mappedType = (item.type as string).replace(/-/g, '_') as FeedItemDTO['type'];

  const dto: FeedItemDTO = {
    id: item.id,
    timestamp:
      item.timestamp instanceof Date
        ? item.timestamp.toISOString()
        : new Date(item.timestamp).toISOString(),
    type: mappedType,
    headline: item.headline,
  };

  if (item.actorFriendId !== undefined) dto.actorFriendId = item.actorFriendId;
  if (item.actorDriverId !== undefined) dto.actorDriverId = item.actorDriverId;
  if (item.leagueId !== undefined) dto.leagueId = item.leagueId;
  if (item.raceId !== undefined) dto.raceId = item.raceId;
  if (item.teamId !== undefined) dto.teamId = item.teamId;
  if (item.position !== undefined) dto.position = item.position;
  if (item.body !== undefined) dto.body = item.body;
  if (item.ctaLabel !== undefined) dto.ctaLabel = item.ctaLabel;
  if (item.ctaHref !== undefined) dto.ctaHref = item.ctaHref;

  return dto;
}