import { Injectable } from '@nestjs/common';
import { TransactionEntity } from '../../domain/entities/transaction.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { TransactionModel } from '../models/transaction.model';
import {
  CONNECTION_NAME,
  STATUS,
} from 'src/core/strings/constants/base.constants';
import { Repository } from 'typeorm';
import { BaseReadService } from 'src/core/modules/data/service/base-read.service';
import { TransactionPaymentType, TransactionType } from '../../constants';

@Injectable()
export class TransactionReadService extends BaseReadService<TransactionEntity> {
  constructor(
    @InjectRepository(TransactionModel, CONNECTION_NAME.DEFAULT)
    private repo: Repository<TransactionModel>,
  ) {
    super(repo);
  }

  async getPendingOrderId() {
    const transactions = await this.repo.find({
      where: {
        status: STATUS.PENDING,
        payment_type: TransactionPaymentType.MIDTRANS,
        type: TransactionType.ONLINE,
      },
      select: ['id', 'invoice_date', 'created_at', 'booking_date'],
    });

    return transactions;
  }

  async getSummary(posId: string, startDate: string) {
    const query = `select payment_type_counter, payment_type_method_name, sum(payment_total) payment_total, sum(payment_total_pay) payment_total_pay
      from transactions t
      where 1=1
      and t.creator_counter_no IN (${posId})
      and invoice_date = '${startDate}'
      and status = 'settled'
      group by payment_type_counter, payment_type_method_name;`;
    const transactions = await this.repo.query(query);

    const qtyQuery = `select ti.item_id, ti.item_name, sum(ti.qty) total_qty, count(ti.item_name), sum(ti.qty), string_agg(distinct ti.item_price::text, '') price,
       sum(payment_total) payment_total, sum(payment_total_pay) payment_total_pay
        from transactions t
        inner join transaction_items ti on t.id = ti.transaction_id
        where t.creator_counter_no IN (${posId})
      and invoice_date = '${startDate}'
      and t.status = 'settled'
      group by ti.item_name, ti.item_id`;
    const qtyTransactions = await this.repo.query(qtyQuery);

    const totalSalesQuery = `select sum(payment_total) payment_total
      from transactions t
      where 1=1
      and t.creator_counter_no IN (${posId})
      and invoice_date = '${startDate}'
      and status = 'settled'`;
    const totalSales = await this.repo.query(totalSalesQuery);

    return {
      payment: transactions,
      qty: qtyTransactions,
      totalSales: totalSales?.[0]?.payment_total ?? 0,
    };
  }

  async getLastTransactionByPos(
    posId: string,
  ): Promise<TransactionEntity | null> {
    const transaction = await this.repo.findOne({
      select: [
        'id',
        'created_at',
        'updated_at',
        'status',
        'invoice_code',
        'creator_counter_no',
        'invoice_date',
        'payment_total',
      ],
      where: {
        creator_counter_no: parseInt(posId),
      },
      order: {
        created_at: 'DESC',
      },
    });

    return transaction;
  }
}
