import * as DataLoader from 'dataloader';
import { Injectable, Scope } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { Child } from '../../database/entities/child.entity';

@Injectable({ scope: Scope.REQUEST })
export class ChildDataLoader {
  constructor(
    @InjectRepository(Child)
    private readonly childRepository: Repository<Child>,
  ) {}

  public readonly batchChildren = new DataLoader<string, Child>(
    async (childIds: readonly string[]) => {
      const children = await this.childRepository.find({
        where: { id: In([...childIds]) },
      });

      const childMap = new Map(children.map((child) => [child.id, child]));
      return childIds.map((id) => childMap.get(id) || null);
    },
  );

  public readonly batchChildrenByFamily = new DataLoader<
    string,
    Child[]
  >(async (familyIds: readonly string[]) => {
    const children = await this.childRepository.find({
      where: { familyId: In([...familyIds]) },
    });

    const childrenByFamily = new Map<string, Child[]>();
    children.forEach((child) => {
      const existing = childrenByFamily.get(child.familyId) || [];
      existing.push(child);
      childrenByFamily.set(child.familyId, existing);
    });

    return familyIds.map((familyId) => childrenByFamily.get(familyId) || []);
  });
}
