import { AppService, Collection } from '@avleon/core';
import { {Model} } from '../models/{model}.model';


@AppService
export class {Service}Service{

  constructor(
    private readonly {model}Collection:Collection.from<{Model}>([])
  ){}

  async findAll(options:any={}){
    return this.{model}Collection.find(options); 
  }

  async paginate(current:number = 1, options:any={}){
    const take = 10;
    const skip = current >  1 ? ( current -1 ) * 10 : 0;
    const total = await this.{model}Collection.count(options);
    const totalPage = Math.ceil(total / take);
    const next = current < totalPage ? current + 1 : null;
    const prev = current > 1 ? current - 1 : null;
    const data = await this.{model}Collection.find({
        ...options,
        take,
        skip
    })

    return {
        total,
        totalPage,
        current,
        next,
        prev,
        data
    };
  }

  async findByPk(id:number){
    return this.{model}Collection.findOne({id});
  }

  async findBy(options:any){
    return this.{model}Collection.findBy(options);
  }

  async findOneBy(options:any){
    return this.{model}Collection.findOneBy(options);
  }


  async findOne(id:number){
    return this.{model}Collection.findOne({where:{id}}) ;
  }

  async create(createBody:any){
    const savedItem = await this.{model}Collection.save(createBody);
    return savedItem;
  }

  async update(id:number, updateBody:any){
    const isUpdate = await this.{model}Collection.update(id, updateBody); 
    return isUpdate;
  }

  async delete(id:number){
    const isDeleted = await this.{model}Collection.delete(id);
    return isDeleted > 0;
  }

}
