import { In, type Repository } from 'typeorm';

import type { IFeedRepository } from '@core/social/domain/repositories/IFeedRepository';
import type { FeedItem } from '@core/social/domain/types/FeedItem';

import { FeedItemOrmEntity } from '../entities/FeedItemOrmEntity';
import { FriendshipOrmEntity } from '../entities/FriendshipOrmEntity';
import { FeedItemOrmMapper } from '../mappers/FeedItemOrmMapper';

export class TypeOrmFeedRepository implements IFeedRepository {
  constructor(
    private readonly feedRepo: Repository<FeedItemOrmEntity>,
    private readonly friendshipRepo: Repository<FriendshipOrmEntity>,
    private readonly mapper: FeedItemOrmMapper,
  ) {}

  async getFeedForDriver(driverId: string, limit?: number): Promise<FeedItem[]> {
    const friendships = await this.friendshipRepo.find({ where: { driverId } });
    const friendIds = friendships.map((f) => f.friendId);

    if (friendIds.length === 0) return [];

    const entities = await this.feedRepo.find({
      where: {
        actorDriverId: In(friendIds),
      },
      order: { timestamp: 'DESC' },
      ...(typeof limit === 'number' ? { take: limit } : {}),
    });

    return entities.map((e) => this.mapper.toDomain(e));
  }

  async getGlobalFeed(limit?: number): Promise<FeedItem[]> {
    const entities = await this.feedRepo.find({
      order: { timestamp: 'DESC' },
      ...(typeof limit === 'number' ? { take: limit } : {}),
    });

    return entities.map((e) => this.mapper.toDomain(e));
  }
}