import { RUNTIME_IMPORT } from '../consts.js';
import type { DBTable, DBTables } from '../types.js';

export function getDtsContent(tables: DBTables) {
	const content = `// This file is generated by Astro DB
declare module 'astro:db' {
${Object.entries(tables)
	.map(([name, table]) => generateTableType(name, table))
	.join('\n')}
}
`;
	return content;
}

function generateTableType(name: string, table: DBTable): string {
	const sanitizedColumnsList = Object.entries(table.columns)
		// Filter out deprecated columns from the typegen, so that they don't
		// appear as queryable fields in the generated types / your codebase.
		.filter(([, val]) => !val.schema.deprecated);
	const sanitizedColumns = Object.fromEntries(sanitizedColumnsList);
	let tableType = `	export const ${name}: import(${RUNTIME_IMPORT}).Table<
		${JSON.stringify(name)},
		${JSON.stringify(sanitizedColumns)}
	>;`;
	return tableType;
}
