import { projectExistsInTable } from "./manage/projects.js";

//#region src/data-access/validation.ts
/**
* Validates that a project exists before performing database operations
* This provides runtime validation even when foreign key constraints are not enforced
*/
const validateProjectExists = async (db, tenantId, projectId) => {
	if (!await projectExistsInTable(db)({ scopes: {
		tenantId,
		projectId
	} })) throw new Error(`Project with ID "${projectId}" does not exist for tenant "${tenantId}". Please create the project first before adding resources to it.`);
};
/**
* Wraps a database operation with project validation
* Ensures the project exists before executing the operation
*/
const withProjectValidation = (db, operation) => {
	return async (params) => {
		const tenantId = params.tenantId || params.scopes?.tenantId;
		const projectId = params.projectId || params.scopes?.projectId;
		if (tenantId && projectId) await validateProjectExists(db, tenantId, projectId);
		return operation(params);
	};
};
/**
* Creates a validated version of data access functions
* Automatically adds project validation to insert/update operations
*/
const createValidatedDataAccess = (db, dataAccessFunctions) => {
	const validated = {};
	for (const [key, fn] of Object.entries(dataAccessFunctions)) if (typeof fn === "function") if (key.startsWith("create") || key.startsWith("insert") || key.startsWith("update")) validated[key] = withProjectValidation(db, fn);
	else validated[key] = fn;
	else validated[key] = fn;
	return validated;
};

//#endregion
export { createValidatedDataAccess, validateProjectExists, withProjectValidation };