import { Op } from "sequelize";
import sequelize from "../../config/database";
import BcAiWebhookQueue from "@database/models/BcAiWebhookQueue";
import { WebhookEnqueueJob } from "./types";
import { mergeScope } from "./mergeScope";

const OPEN_STATUSES = ["pending", "processing"];

export async function enqueueBcWebhook(job: WebhookEnqueueJob): Promise<void> {
	await sequelize.transaction(async (transaction) => {
		const existing = await BcAiWebhookQueue.findOne({
			where: {
				websiteId: job.websiteId,
				entityType: job.entityType,
				entityId: job.entityId,
				status: { [Op.in]: OPEN_STATUSES },
			},
			transaction,
			lock: transaction.LOCK.UPDATE,
		});

		if (existing) {
			const scope = mergeScope(existing.scope, job.scope);
			await existing.update(
				{
					scope,
					payload: job.payload,
				},
				{ transaction }
			);
			return;
		}

		await BcAiWebhookQueue.create(
			{
				websiteId: job.websiteId,
				scope: job.scope,
				entityType: job.entityType,
				entityId: job.entityId,
				payload: job.payload,
				status: "pending",
				attempts: 0,
			},
			{ transaction }
		);
	});
}
