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

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

export const handler: SessionHandlers = {
	async GET() {
		try {
			const preCachedUrls: string[] = ['/', '/imports/markdown_css']
			const paths = ['/static/**', '/_fresh/static/**']
			const routes = '/routes/*/index.tsx'
			const version = BUILD_ID

			//Pre-cache routes
			for await (const route of expandGlob(routes, { root: '.' })) {
				if ('isFile' in route && !route.isFile) continue
				preCachedUrls.push(strip('/routes/**', route.path))
			}

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

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

function strip(root: string, path: string) {
	// Remove root slash and glob *
	const base = root.slice(1).replaceAll('*', '').replaceAll('\\', '/')
	// Force unix/web separator
	const pathname = path.replaceAll('\\', '/').replace('/index.tsx', '')

	return `/${pathname.slice(base.length)}`
}
