import { db } from '../db';
import { Client } from '../client';
import { UUID } from '../global/scalars/UUID';
import { v4 as uuid } from 'uuid';

export abstract class Service<E> {
  protected collection: string = '';

  public async findOneById(id: UUID): Promise<E> {
    const data = await db.fetch(this.collection, { _id: id });

    return data?.[0] || null as E;
  }

  public async find(filter: any, limit?: number, offset?: number): Promise<E[]> {
    return db.fetch(this.collection, filter, limit, offset);
  }

  public async update(client: Client, id: UUID, ops: any, filter?: any): Promise<E> {
    return db.doOps(this.collection, id, ops, filter, client);
  }

  protected async insert(client: Client, doc: any): Promise<E> {
    doc._id = uuid();

    return db.insert(this.collection, doc, client);
  }
}