import { Injectable } from '@nestjs/common';

import { InjectRepository } from '@nestjs/typeorm';
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
import { Between, Repository } from 'typeorm';
import { BaseReadService } from 'src/core/modules/data/service/base-read.service';
import { QueueBucketModel } from '../models/queue-bucket.model';
import * as moment from 'moment';
import { QueueItemModel } from '../models/queue.model';

@Injectable()
export class QueueBucketReadService extends BaseReadService<QueueBucketModel> {
  constructor(
    @InjectRepository(QueueBucketModel, CONNECTION_NAME.DEFAULT)
    private repo: Repository<QueueBucketModel>,

    @InjectRepository(QueueItemModel, CONNECTION_NAME.DEFAULT)
    private item: Repository<QueueItemModel>,
  ) {
    super(repo);
  }

  async getQueue(item_id: string, vip = false): Promise<number> {
    const start = moment().startOf('day').valueOf();
    const end = moment().endOf('day').valueOf();

    const queue = await this.repo.findOne({
      where: {
        queue_item_id: item_id,
        date: Between(start, end),
      },
    });

    if (!queue) {
      const regularNumber = vip ? 0 : 1;
      const vipNumber = vip ? 1 : 0;
      await this.repo.save({
        queue_item_id: item_id,
        date: start,
        regular: regularNumber,
        vip: vipNumber,
      });
      return Promise.resolve(1);
    } else {
      const field = vip ? 'vip' : 'regular';
      const data = await this.repo
        .createQueryBuilder('bucket')
        .update(QueueBucketModel)
        .set({
          [field]: () => `${field} + 1`,
        })
        .where('id = :key', {
          key: queue.id,
        })
        .returning(field)
        .updateEntity(true)
        .execute();

      return data.raw[0]?.[field] ?? 1;
    }
  }
}
