import type { GetServerSideProps } from "next";
import CheckoutForm from "~/components/checkout";
import { AreaRiservataLayout } from "~/components/Layout";
import stripe from "~/lib/stripe";
import { redirectTo500 } from "~/lib/utils";
import type { NextPageWithLayout } from "~/pages/_app";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zOrdineId } from "~/server/utils/zod_types";

type PagamentoPageProps = {
	clientSecret: string | null;
	titolo: string;
	prezzo: number;
	descrizione: string;
};

/**
 * /servizio/pagamento-checkout/[ordineId] \
 * Pagina di checkout per il pagamento di un ordine di servizio. Riceve l'ordineId, recupera i dati necessari e crea un PaymentIntent su Stripe, quindi passa il clientSecret al componente di checkout.
 */
const PagamentoPage: NextPageWithLayout<PagamentoPageProps> = ({
	clientSecret,
	titolo,
	prezzo,
	descrizione,
}: PagamentoPageProps) => {
	if (!clientSecret) {
		return <div>Errore nella creazione del pagamento. Riprova più tardi.</div>;
	}
	return (
		<div className="mx-auto my-5 w-full max-w-lg space-y-8" id="checkout">
			<CheckoutForm
				clientSecret={clientSecret}
				descrizione={descrizione}
				prezzo={prezzo}
				titolo={titolo}
			/>
		</div>
	);
};

PagamentoPage.getLayout = function getLayout(page) {
	return <AreaRiservataLayout noSidebar>{page}</AreaRiservataLayout>;
};

export default PagamentoPage;

export const getServerSideProps = (async (context) => {
	const id = context.params?.ordineId;
	if (typeof id !== "string") {
		console.error("Error: ordineId is not a string");
		return redirectTo500;
	}

	const parsed = zOrdineId.safeParse(id);
	if (!parsed.success) {
		console.error("Error parsing ordineId", parsed.error);
		return redirectTo500;
	}

	const access_token = context.req.cookies.access_token;

	const helper = await TrpcAuthedFetchingIstance({ access_token });
	if (helper) {
		const paymentData =
			await helper.trpc.pagamenti.getPagamentoDataForCheckout.fetch({
				ordineId: parsed.data,
			});

		const customer = await stripe.customers.create({
			email: paymentData.email,
			name: paymentData.username,
			description: paymentData.username,
			metadata: {
				userId: paymentData.userid,
			},
		});

		const { client_secret: clientSecret } = await stripe.paymentIntents.create({
			amount: paymentData.amount_cent,

			automatic_payment_methods: {
				enabled: true,
			},
			currency: "eur",
			customer: customer.id,
			description: paymentData.nome_it,
			metadata: {
				ordineId: paymentData.ordine_id,
				userId: paymentData.userid,
			},

			receipt_email: paymentData.email,
		});

		if (!clientSecret) {
			return redirectTo500;
		}

		return {
			props: {
				clientSecret,
				titolo: paymentData.nome_it,
				prezzo: paymentData.amount_cent,
				descrizione: paymentData.desc_it,
			},
		};
	}
	return redirectTo500;
}) satisfies GetServerSideProps<PagamentoPageProps>;
