import { Injectable } from '@nestjs/common';
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
import { SelectQueryBuilder } from 'typeorm';
import {
  Param,
  RelationParam,
} from 'src/core/modules/domain/entities/base-filter.entity';
import { Queue } from '../entities/queue.entity';
import * as moment from 'moment';
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
import { QueueTimeFormula } from './formula/queue-time.formula';

@Injectable()
export class IndexQueueManager extends BaseIndexManager<Queue> {
  constructor(private readonly queueTimeFormula: QueueTimeFormula) {
    super();
  }

  private queueTimes = {};
  async prepareData(): Promise<void> {
    return;
  }

  async beforeProcess(): Promise<void> {
    return;
  }

  async afterProcess(): Promise<void> {
    this.queueTimes = await this.queueTimeFormula.items(
      this.filterParam.queue_id,
    );
    return;
  }

  get relations(): RelationParam {
    return {
      joinRelations: [],
      selectRelations: ['item', 'item.ticket'],
      countRelations: [],
    };
  }

  getResult(): PaginationResponse<Queue> {
    const result = this.result;

    return {
      total: result.total,
      data: result.data.map((queue) => {
        return {
          ...queue,
          estimation: this.queueTimes[queue.id],
        };
      }),
    };
  }

  get selects(): string[] {
    return [
      `${this.tableName}.id`,
      `${this.tableName}.code`,
      `${this.tableName}.status`,
      `${this.tableName}.time`,
      `${this.tableName}.call_time`,
      `${this.tableName}.vip`,
      `${this.tableName}.item`,
      `${this.tableName}.qty`,
      `${this.tableName}.created_at`,

      `item.id`,
      `ticket.customer`,
      `ticket.phone`,
    ];
  }

  get specificFilter(): Param[] {
    return [
      {
        cols: `${this.tableName}.status`,
        data: this.filterParam.status,
      },
    ];
  }

  setQueryFilter(
    queryBuilder: SelectQueryBuilder<Queue>,
  ): SelectQueryBuilder<Queue> {
    const start = moment().startOf('day').valueOf();
    const end = moment().endOf('day').valueOf();

    console.log({ start, end, item_queue_id: this.filterParam.queue_id });

    queryBuilder.andWhere(
      `${this.tableName}.created_at BETWEEN :start AND :end`,
      {
        start,
        end,
      },
    );

    queryBuilder.andWhere(`${this.tableName}.item_queue_id = :item_queue_id`, {
      item_queue_id: this.filterParam.queue_id,
    });

    if (this.filterParam.vip != null) {
      queryBuilder.andWhere(`${this.tableName}.vip = :vip`, {
        vip: this.filterParam.vip,
      });
    }
    return queryBuilder;
  }
}
