import { Request, Response } from 'express'
import path from 'path'
import { Payment } from './models'
import services from '../../utils/services'
import helpers from '../../utils/helpers'

async function postWebhook(req: Request, res: Response) {
	res.status(200).json({ message: 'ok' })

	await helpers.runApi(res, async () => {
		const body = req.body as any
		let checkoutSessionId: string | undefined

		// Stripe event format: { type, data: { object: { id } } }
		if (body?.data?.object?.id) {
			checkoutSessionId = body.data.object.id
		} else if (body?.checkoutSessionId) {
			checkoutSessionId = body.checkoutSessionId
		}

		if (!checkoutSessionId) {
			console.log('400: checkout session id required')
			return
		}

		const payment = await Payment.findOne({ stripeCheckoutId: checkoutSessionId })
		if (!payment) {
			console.log('404: payment not found')
			return
		}

		await services.managePayment(payment)
		console.log('200: ok')
	})
}

function getSuccessPage(_req: Request, res: Response) {
	return res.sendFile(path.join(__dirname, 'payment-success-page.html'))
}

const controllers = {
	postWebhook,
	getSuccessPage
}

export default controllers
