import type { FindOptionsOrder, FindOptionsWhere } from 'typeorm';
import { TenantAwareRepository } from '../repositories/tenant-aware.repository';
import type { BaseMediaEntity } from './base-media.entity';

/**
 * Base for every `{module}_media` repository. `parentColumn` names the
 * FK to the owning record so {@link MediaService} can work against any
 * of the per-module tables without knowing which one it is.
 */
export abstract class MediaRepository<T extends BaseMediaEntity> extends TenantAwareRepository<T> {
  abstract readonly parentColumn: string;

  findForParent(parentId: string): Promise<T[]> {
    return this.find({
      where: { [this.parentColumn]: parentId } as FindOptionsWhere<T>,
      order: { sort_order: 'ASC', created_at: 'ASC' } as FindOptionsOrder<T>,
    });
  }

  findByUrl(url: string): Promise<T | null> {
    return this.findOne({ where: { url } as FindOptionsWhere<T> });
  }

  parentIdOf(row: T): string {
    return (row as unknown as Record<string, string>)[this.parentColumn];
  }
}
