var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import BillingService from "./BillingService";
import DatabaseService from "./DatabaseService";
import ProjectService from "./ProjectService";
import URL from "../../Types/API/URL";
import { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import BadDataException from "../../Types/Exception/BadDataException";
import Model, { InvoiceStatus, } from "../../Models/DatabaseModels/BillingInvoice";
import SubscriptionStatus, { SubscriptionStatusUtil, } from "../../Types/Billing/SubscriptionStatus";
import Semaphore from "../Infrastructure/Semaphore";
import logger from "../Utils/Logger";
import OneUptimeDate from "../../Types/Date";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
        this.setDoNotAllowDelete(true);
    }
    async refreshSubscriptionStatus(data) {
        var _a, _b, _c;
        let mutex = null;
        try {
            mutex = await Semaphore.lock({
                key: data.projectId.toString(),
                namespace: "BillingInoviceService.refreshSubscriptionStatus",
                lockTimeout: 15000,
                acquireTimeout: 20000,
            });
            logger.debug("Mutex acquired - " +
                data.projectId.toString() +
                " at " +
                OneUptimeDate.getCurrentDateAsFormattedString());
        }
        catch (err) {
            logger.debug("Mutex acquire failed - " +
                data.projectId.toString() +
                " at " +
                OneUptimeDate.getCurrentDateAsFormattedString());
            logger.error(err, {
                projectId: (_a = data.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
            });
        }
        const project = await ProjectService.findOneById({
            id: data.projectId,
            props: {
                isRoot: true,
            },
            select: {
                _id: true,
                paymentProviderCustomerId: true,
                paymentProviderSubscriptionId: true,
                paymentProviderMeteredSubscriptionId: true,
            },
        });
        /*
         * refresh the subscription status. This is a hack to ensure that the subscription status is always up to date.
         * This is because the subscription status can change at any time and we need to ensure that the subscription status is always up to date.
         */
        if (!project) {
            throw new BadDataException("Project not found");
        }
        if (!project.paymentProviderCustomerId) {
            throw new BadDataException("Payment provider customer id not found.");
        }
        const subscriptionState = await BillingService.getSubscriptionStatus(project.paymentProviderSubscriptionId);
        const meteredSubscriptionState = await BillingService.getSubscriptionStatus(project.paymentProviderMeteredSubscriptionId);
        // update the project.
        await ProjectService.updateOneById({
            id: project.id,
            data: {
                paymentProviderSubscriptionStatus: subscriptionState,
                paymentProviderMeteredSubscriptionStatus: meteredSubscriptionState,
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
        });
        if (SubscriptionStatusUtil.isSubscriptionInactive(meteredSubscriptionState) ||
            SubscriptionStatusUtil.isSubscriptionInactive(subscriptionState)) {
            // check if all invoices are paid. If yes, then reactivate the subscription.
            const invoices = await BillingService.getInvoices(project.paymentProviderCustomerId);
            let allInvoicesPaid = true;
            for (const invoice of invoices) {
                if (invoice.status === InvoiceStatus.Open ||
                    invoice.status === InvoiceStatus.Uncollectible) {
                    allInvoicesPaid = false;
                    break;
                }
            }
            if (allInvoicesPaid) {
                try {
                    await ProjectService.reactiveSubscription(project.id);
                }
                catch (err) {
                    logger.error(err, {
                        projectId: (_b = data.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                    });
                }
                /*
                 * No Open/Uncollectible invoices means the project has no outstanding
                 * payment obligations, so we mark the subscription as Active. Stripe may
                 * still report the (re)created subscription as "incomplete" until the
                 * first payment confirms, which would otherwise surface a misleading
                 * "invoices are unpaid" banner.
                 */
                await ProjectService.updateOneById({
                    id: project.id,
                    data: {
                        paymentProviderSubscriptionStatus: SubscriptionStatus.Active,
                        paymentProviderMeteredSubscriptionStatus: SubscriptionStatus.Active,
                    },
                    props: {
                        isRoot: true,
                        ignoreHooks: true,
                    },
                });
            }
        }
        if (mutex) {
            try {
                await Semaphore.release(mutex);
                logger.debug("Mutex released - " +
                    data.projectId.toString() +
                    " at " +
                    OneUptimeDate.getCurrentDateAsFormattedString());
            }
            catch (err) {
                logger.debug("Mutex release failed - " +
                    data.projectId.toString() +
                    " at " +
                    OneUptimeDate.getCurrentDateAsFormattedString());
                logger.error(err, {
                    projectId: (_c = data.projectId) === null || _c === void 0 ? void 0 : _c.toString(),
                });
            }
        }
    }
    async onBeforeFind(findBy) {
        if (!findBy.props.tenantId) {
            throw new BadDataException("ProjectID not found.");
        }
        const project = await ProjectService.findOneById({
            id: findBy.props.tenantId,
            props: Object.assign(Object.assign({}, findBy.props), { isRoot: true, ignoreHooks: true }),
            select: {
                _id: true,
                paymentProviderCustomerId: true,
            },
        });
        /*
         * refresh the subscription status. This is a hack to ensure that the subscription status is always up to date.
         * This is because the subscription status can change at any time and we need to ensure that the subscription status is always up to date.
         */
        await this.refreshSubscriptionStatus({ projectId: findBy.props.tenantId });
        if (!project) {
            throw new BadDataException("Project not found");
        }
        if (!project.paymentProviderCustomerId) {
            throw new BadDataException("Payment provider customer id not found.");
        }
        const invoices = await BillingService.getInvoices(project.paymentProviderCustomerId);
        await this.deleteBy({
            query: {
                projectId: findBy.props.tenantId,
            },
            limit: LIMIT_PER_PROJECT,
            skip: 0,
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
        });
        for (const invoice of invoices) {
            const billingInvoice = new Model();
            billingInvoice.projectId = project.id;
            billingInvoice.amount = invoice.amount;
            billingInvoice.downloadableLink = URL.fromString(invoice.downloadableLink);
            billingInvoice.currencyCode = invoice.currencyCode;
            billingInvoice.paymentProviderCustomerId = invoice.customerId || "";
            billingInvoice.paymentProviderSubscriptionId =
                invoice.subscriptionId || "";
            billingInvoice.status =
                invoice.status || InvoiceStatus.Undefined;
            billingInvoice.paymentProviderInvoiceId = invoice.id;
            billingInvoice.invoiceDate = invoice.invoiceDate;
            billingInvoice.invoiceNumber = invoice.invoiceNumber || "Unknown";
            await this.create({
                data: billingInvoice,
                props: {
                    isRoot: true,
                },
            });
        }
        return { findBy, carryForward: invoices };
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "refreshSubscriptionStatus", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeFind", null);
export default new Service();
//# sourceMappingURL=BillingInvoiceService.js.map