import { Injectable } from "@nestjs/common";
import { DataSource, FindOptionsWhere, QueryDeepPartialEntity, QueryRunner, Repository } from "typeorm";
import { PaymentEntity } from "./entities/payment.entity";

@Injectable()
export class PaymentRepository {
    private readonly paymentRepo: Repository<PaymentEntity>;
    constructor(private readonly dataSource: DataSource) {
        this.paymentRepo = this.dataSource.getRepository(PaymentEntity)
    }

    async createTr(qr: QueryRunner, data: Pick<PaymentEntity, "amount" | "method" | "currency" | "type" | "refId" | "merchantOrderId" | "rawInitiation" | "clientAction" | "expiresAt" | "reason">): Promise<PaymentEntity> {
        const payment = qr.manager.create(PaymentEntity, data)
        return qr.manager.save(payment)
    }

    async create(data: Pick<PaymentEntity, "amount" | "method" | "currency" | "type" | "refId" | "merchantOrderId" | "rawInitiation" | "clientAction" | "expiresAt" | "reason">): Promise<PaymentEntity> {
        const payment = this.paymentRepo.create(data)
        return this.paymentRepo.save(payment)
    }



    findOneBy(options: FindOptionsWhere<PaymentEntity> | FindOptionsWhere<PaymentEntity>[]): Promise<PaymentEntity | null> {
        return this.paymentRepo.findOneBy(options);
    }

    update(where: FindOptionsWhere<PaymentEntity>, data: QueryDeepPartialEntity<PaymentEntity>) {
        return this.paymentRepo.update(where, data)
    }

    getActivePaymentByRefIdAndMethod(refId: string, method: PaymentEntity["method"]) {
        return this.paymentRepo
            .createQueryBuilder('payment')
            .where('payment.method = :method', { method })
            .andWhere('payment.refId = :refId', { refId })
            .andWhere('payment.status IN (:...statuses)', {
                statuses: ['action-required'],
            })
            .andWhere('payment.expiresAt > :now', { now: new Date() })
            .getOne();
    }





    getActivePaymentByOrderIdAndMethod(orderId: string, method: PaymentEntity["method"]) {
        return this.paymentRepo
            .createQueryBuilder('payment')
            .where('payment.method = :method', { method })
            .andWhere('payment.merchantOrderId = :orderId', { orderId })
            .andWhere('payment.status IN (:...statuses)', {
                statuses: ['action-required'],
            })
            .andWhere('payment.expiresAt > :now', { now: new Date() })
            .getOne();
    }



}