namespace _espe.database
{
	
	/**
	 */
	const _compatible_revisions : Array<string> = [
		"r1",
	];
	
		
	/**
	 */
	export function get_implementation(
	) : lib_plankton.database.type_database
	{
		switch (_espe.conf.get().database.kind) {
			case "sqlite": {
				return lib_plankton.database.sqlite_database(
					{
						"path": _espe.conf.get().database.data["path"],
						"verbose": false,
					}
				);
				break;
			}
			default: {
				throw (new Error("database implementation not available: " + _espe.conf.get().database.kind));
			}
		}
	}
	
	
	/**
	 */
	function get_revision(
	) : Promise<(null | string)>
	{
		return (
			get_implementation().query_select(
				{
					"source": "_meta",
					"fields": ["revision"],
				}
			)
			.then<(null | string)>(
				(rows) => Promise.resolve<(null | string)>(rows[0]["revision"])
			)
			.catch<(null | string)>(
				() => Promise.resolve<(null | string)>(null)
			)
		);
	}
	
	
	/**
	 */
	export async function check(
	) : Promise<void>
	{
		const revision : (null | string) = await get_revision();
		lib_plankton.log.info(
			"database_check",
			{
				"revision_found": revision,
				"revisions_compatible": _compatible_revisions,
			}
		);
		if (revision === null) {
			return Promise.reject<void>(new Error("database appearently missing"));
		}
		else {
			if (! _compatible_revisions.includes(revision)) {
				return Promise.reject<void>(new Error("database revision incompatible; found: " + revision + "; required: " + String(_compatible_revisions)));
			}
			else {
				return Promise.resolve<void>(undefined);
			}
		}
	}
	
}
