import { applicationErrorResponse, sendFailedResponse, sendSuccessResponse } from "@lib/responses";
import { authenticateAPIToken } from "@middleware/authentication";
import { NextApiResponse } from "next";

/**
 * Regenerates storefront userData JSON (uniqueId.json on GCS): filters, badges,
 * discountRules, categoryAccessByGroupId, merchandising flags, etc.
 * Proxies to sbend generateWebsiteJson via refreshStorefrontMerchandisingJson.
 */
export default async function handler(req: any, res: NextApiResponse) {
	if (req.method !== "POST") {
		return res.status(405).json({ message: "Method not allowed" });
	}

	authenticateAPIToken(req, res, async () => {
		try {
			if (!req.websiteId) {
				return sendFailedResponse(res, {}, "No store found");
			}

			const rawResponse = await fetch(
				`${process.env.CBEND_URL}/api/v1/website/refreshStorefrontMerchandisingJson`,
				{
					method: "POST",
					headers: {
						Accept: "application/json",
						"Content-Type": "application/json",
					},
					body: JSON.stringify({ websiteId: req.websiteId }),
				}
			);

			const content = await rawResponse.json();

			if (content.status === "success") {
				const userDataBase = process.env.USER_DATA_URL
					? String(process.env.USER_DATA_URL).replace(/\/$/, "")
					: null;
				const uniqueId = content.data?.uniqueId ?? null;
				return sendSuccessResponse(
					res,
					{
						websiteId: req.websiteId,
						uniqueId,
						userDataJsonUrl: uniqueId && userDataBase ? `${userDataBase}/${uniqueId}.json` : null,
					},
					content.message || "Storefront JSON generated successfully"
				);
			}

			return sendFailedResponse(
				res,
				content.data || {},
				content.message || "Failed to generate storefront JSON"
			);
		} catch (e) {
			console.log(e);
			return applicationErrorResponse(res);
		}
	});
}
