import { Injectable } from '@nestjs/common';
import { BaseDataService } from 'src/core/modules/data/service/base-data.service';
import { InjectRepository } from '@nestjs/typeorm';
import { TransactionModel } from '../models/transaction.model';
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
import { Repository } from 'typeorm';
import { CouchService } from 'src/modules/configuration/couch/data/services/couch.service';

@Injectable()
export class TransactionDataService extends BaseDataService<TransactionModel> {
  constructor(
    @InjectRepository(TransactionModel, CONNECTION_NAME.DEFAULT)
    private repo: Repository<TransactionModel>,
    private couchService: CouchService,
  ) {
    super(repo);
  }

  async getTransactionWithReschedule(booking_id: string) {
    return this.repo.findOne({
      relations: ['children_transactions', 'items'],
      where: { id: booking_id },
    });
  }

  async saveTransactionToCouch(transaction) {
    const id = transaction.id ?? transaction._id;
    const couchData = await this.couchService.getDoc(id, 'transaction');
    if (!couchData) {
      await this.couchService.createDoc(transaction, 'transaction');
    } else {
      await this.couchService.updateDoc(transaction, 'transaction');
    }
  }
}
