import { SessionHandlers } from ':src/session/mod.ts'
import { respondApi } from ':src/utils.ts'
import { expandGlob } from '$std/fs/mod.ts'

export type PrecacheResponse = { version: string; files: string[] }

// Updated only at server start
const version = crypto.randomUUID()

export const handler: SessionHandlers = {
	async GET() {
		try {
			const files: string[] = ['/', '/imports/markdown_css']
			const paths = ['/static/**', '/_fresh/static/**']
			const routes = '/routes/*'

			//Pre-cache routes
			for await (const route of expandGlob(routes, { root: '.' })) {
				if (!route.isDirectory) continue
				if (route.name === 'api') continue
				if (route.name === 'imports') continue

				files.push(strip(routes, route))
			}

			// Pre-cache files
			for (const path of paths) {
				for await (const entry of expandGlob(path, { root: '.' })) {
					if (entry.isFile) {
						files.push(strip(path, entry))
					}
				}
			}

			return respondApi<'success', PrecacheResponse>('success', {
				version,
				files,
			})
		} catch (error) {
			return respondApi('error', error)
		}
	},
}

function strip(root: string, { path }: { path: string }) {
	return path
		// Force unix/web separator
		.replaceAll('\\', '/')
		.replace(
			// Remove root slash and glob *
			root.slice(1).replaceAll('*', ''),
			'/',
		)
}
