import type { JsonValue } from '@std/json'
import defaultAccounts from './account.json' with { type: 'json' }
import defaultDkim from './dkim.json' with { type: 'json' }

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

type JsonRecord = Record<string, JsonValue>
export type DkimRecord = {
	domainName: string
	keySelector: string
	privateKey: string
}
export type AccountRecord = Record<string, {
	name: string
	address: string
}>

async function readJsonFile<
	T extends JsonRecord,
>(path: string, defaultValue: T): Promise<T> {
	const file = await Deno.readTextFile(path).catch(checkFsErrors)
	const json = JSON.parse(file ?? '{}')
	return { ...defaultValue, ...json }
}

const basePath = '/ect/cohabit/mailer/config'

export const accounts = await readJsonFile<AccountRecord>(
	`${basePath}/account.json`,
	defaultAccounts,
)
export const dkim = await readJsonFile<DkimRecord>(
	`${basePath}/dkim.json`,
	defaultDkim,
)