import { BaseRepository } from "@edr/api-common";
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";

import { FileRecord } from "./entities/file.entity";

@Injectable()
export class FilesRepository extends BaseRepository<FileRecord> {
  constructor(
    @InjectRepository(FileRecord)
    repository: Repository<FileRecord>,
  ) {
    super(repository);
  }

  findByResource(resourceId: string, resource: string): Promise<FileRecord[]> {
    return this.repository.find({ where: { resourceId, resource } });
  }

  findByCode(
    resourceId: string,
    resource: string,
    code: string,
  ): Promise<FileRecord | null> {
    return this.repository.findOne({ where: { resourceId, resource, code } });
  }

  async deleteByCode(
    resourceId: string,
    resource: string,
    code: string,
  ): Promise<void> {
    await this.repository.delete({ resourceId, resource, code });
  }
}
