import { Repository, DeepPartial } from "typeorm";
import { AppDataSource } from "../data-source.js";
import { AbstractEntity } from "../entities/AbstractEntity.js";

/**
 * Basic methods for saving, loading and deleting data
 */
export abstract class AbstractRepository<T extends AbstractEntity> {
  protected repo: Repository<T>;

  constructor(entity: { new (): T }) {
    this.repo = AppDataSource.getRepository(entity);
  }

  async findById(id: string): Promise<T | null> {
    return this.repo.findOne({ where: { id } as any });
  }

  async findAll(): Promise<T[]> {
    return this.repo.find();
  }

  async create(data: DeepPartial<T>): Promise<T> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async delete(id: string): Promise<void> {
    await this.repo.delete(id as any);
  }

  async update(entity: T): Promise<T> {
  return this.repo.save(entity);
}

}
