import axios from "axios";
import moment from "moment";

export async function POST(request: Request) {
	const {id, product} = (await request.json()) as {id: string; product: string};

	if (!id || !product) {
		return Response.json({error: "Product and/or id missing from the body."}, {status: 400});
	}

	try {
		const idChecker = await axios.get(`https://api.stripe.com/v1/checkout/sessions/${id}`, {
			auth: {username: process.env.STRIPE_SECRET || "", password: ""},
		});

		if (idChecker.data["payment_status"] !== "paid") {
			return Response.json({error: "The payment has not yet finished!"}, {status: 401});
		}

		const productChecker = await axios.get(`https://api.stripe.com/v1/products/${product}`, {
			auth: {username: process.env.STRIPE_SECRET || "", password: ""},
		});

		const email = idChecker.data["customer_details"]["email"];

		const days = productChecker.data["metadata"]["expiry_days"];

		await axios.post(process.env.WEBHOOK_URL || "", {days, email, key: process.env.STRIPE_SECRET, checkout: id});

		return Response.json({error: null, ok: true});
	} catch (e) {
		return Response.json({error: "Something went wrong or one of the values is invalid!"}, {status: 500});
	}
}
