import { NextApiRequest, NextApiResponse } from "next";
import BigCommerceSessions from "@database/models/BigCommerceSessions";
import {
	applicationErrorResponse,
	sendBadResponse,
	sendFailedResponse,
	sendSuccessResponse,
} from "@lib/responses";

/**
 * POST /api/aiassistant/createContentImport
 * Body: { storeHash: string }
 *
 * Callable via curl (not embedded-app context). Resolves websiteId via CBEND bigcommerceCheck, then starts content import.
 */
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (req.method !== "POST") {
		return sendBadResponse(res, "Method not allowed. Use POST");
	}

	try {
		const { storeHash } = req.body;

		if (!storeHash || typeof storeHash !== "string") {
			return sendBadResponse(res, "storeHash is required");
		}

		const bigCommerceSession = await BigCommerceSessions.findOne({ where: { storeHash } });

		if (!bigCommerceSession) {
			return sendFailedResponse(res, {}, "Store session not found");
		}

		const accessToken = bigCommerceSession.dataValues.accessToken;

		const checkResponse = await fetch(`${process.env.CBEND_URL}/api/v1/website/bigcommerceCheck`, {
			method: "POST",
			headers: {
				Accept: "application/json",
				"Content-Type": "application/json",
			},
			body: JSON.stringify({
				storeHash,
				accessToken,
				productType: "aiassistant",
			}),
		});

		const checkData = await checkResponse.json();

		if (checkData.status !== "success" || checkData.data?.websiteId == null) {
			return sendFailedResponse(
				res,
				{},
				checkData.message || "Website details not found for AI Assistant"
			);
		}

		const websiteId = checkData.data.websiteId;

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

		const content = await rawResponse.json();

		if (content.status === "success") {
			return sendSuccessResponse(
				res,
				content.data ?? {},
				content.message || "Content import started successfully"
			);
		}
		return sendFailedResponse(res, {}, content.message || "Failed to start content import");
	} catch (e) {
		console.log(e);
		return applicationErrorResponse(res);
	}
}
