import PocketBase from 'pocketbase'

import { defineMiddleware } from 'astro/middleware'
import { getEnv } from 'libs/Env'

export const onRequest = defineMiddleware(async ({ locals, cookies}, next) => {
	locals.pb = new PocketBase(getEnv('POCKETBASE_URL','http://localhost:8080'))

	// load the store data from the request cookie string
	const pbcookie = cookies.get('session')?.value
	locals.pb.authStore.loadFromCookie('pb_auth=' + pbcookie || '')

	try {
		// get an up-to-date auth store state by verifying and refreshing the loaded auth model (if any)
		// eslint-disable-next-line @typescript-eslint/no-unused-expressions
		locals.pb.authStore.isValid && await locals.pb.collection('users').authRefresh()
	} catch (_) {
		// clear the auth store on failed refresh
		locals.pb.authStore.clear()
	}

	const response = await next()

	let secure = true
	if (getEnv('NODE_ENV', 'production') !== 'production') {
		secure = false
	}
	const pbcookieStr = locals.pb.authStore.exportToCookie()

	cookies.set('session',pbcookieStr.slice(pbcookieStr.indexOf('=')+1,pbcookieStr.indexOf(';')),{
		httpOnly: true,
		path: '/',
		secure: secure,
		sameSite: 'lax',
		maxAge: 365000
	})

	return response
})
