import { exists } from '@std/fs/exists'
import type { JSX } from 'preact'
import { EnumType } from '@cliffy/command'
import type { Template } from '../types.ts'
import * as defaultTemplates from '../templates/mod.ts'

export const templates: Map<
	string,
	Template<
		(props: Record<string, unknown>) => JSX.Element,
		Record<string, unknown>
	>
> = new Map()

//Load default templates
for (const template of Object.values(defaultTemplates)) {
	//@ts-expect-error types are checked at runtime later
	templates.set(template.name, template)
}

//Load local templates
const basePath = '/etc/cohabit/mailer/templates'

if (await exists(basePath)) {
	for await (const template of Deno.readDir(basePath)) {
		if (!template.isFile) continue
		if (!template.name.endsWith('.tsx')) continue
		if (template.name.startsWith('_')) continue

		const mod = await import(`${basePath}/${template.name}`).catch(
			checkFsErrors,
		)
		templates.set(mod.default.name, mod.default)
	}
}

function checkFsErrors(error: Error) {
	if (error instanceof Deno.errors.PermissionDenied) {
		throw new Error(
			'unable to load config file due to read access permissions issues',
			{
				cause: error,
			},
		)
	}
	throw error
}

export const templateType = new EnumType([...templates.keys()])