import { MAX_ID_LENGTH, MIN_ID_LENGTH, URL_SAFE_ID_PATTERN } from "./schemas/shared.js";
import { z } from "@hono/zod-openapi";
import { createInsertSchema as createInsertSchema$1, createSelectSchema as createSelectSchema$1 } from "drizzle-zod";

//#region src/validation/drizzle-schema-helpers.ts
function createSelectSchemaWithModifiers(table, overrides) {
	if (!table._?.columns) return createSelectSchema$1(table, overrides);
	throw new Error("Unexpected \"tableColumns\" is defined");
}
function createInsertSchemaWithModifiers(table, overrides) {
	if (!table._?.columns) return createInsertSchema$1(table, overrides);
	throw new Error("Unexpected \"tableColumns\" is defined");
}
const createSelectSchema = createSelectSchemaWithModifiers;
const createInsertSchema = createInsertSchemaWithModifiers;
/**
* Registers all field schemas in an object schema that match known field names.
* This ensures metadata persists through transformations like .partial() and .omit().
* For the 'id' field, also applies full validation constraints via .openapi().
*
* This function registers each field schema instance in the global registry using .meta(),
* and ensures OpenAPI metadata is set via .openapi() for proper documentation generation.
*
* Note: This modifies the schemas in place by registering them in the global registry.
* The schema shape itself is not modified, but the field schemas are registered.
*/
function registerFieldSchemas(schema) {
	if (!(schema instanceof z.ZodObject)) return schema;
	const shape = schema.shape;
	const fieldMetadata = {
		id: { description: "Resource identifier" },
		name: { description: "Name" },
		description: { description: "Description" },
		tenantId: { description: "Tenant identifier" },
		projectId: { description: "Project identifier" },
		agentId: { description: "Agent identifier" },
		subAgentId: { description: "Sub-agent identifier" },
		createdAt: { description: "Creation timestamp" },
		updatedAt: { description: "Last update timestamp" }
	};
	for (const [fieldName, fieldSchema] of Object.entries(shape)) if (fieldName in fieldMetadata && fieldSchema) {
		let zodFieldSchema = fieldSchema;
		let innerSchema = null;
		if (zodFieldSchema instanceof z.ZodOptional) {
			innerSchema = zodFieldSchema._def.innerType;
			zodFieldSchema = innerSchema;
		}
		zodFieldSchema.meta(fieldMetadata[fieldName]);
		if (fieldName === "id" && zodFieldSchema instanceof z.ZodString) zodFieldSchema.openapi({
			description: "Resource identifier",
			minLength: MIN_ID_LENGTH,
			maxLength: MAX_ID_LENGTH,
			pattern: URL_SAFE_ID_PATTERN.source,
			example: "resource_789"
		});
		else if (zodFieldSchema instanceof z.ZodString) zodFieldSchema.openapi({ description: fieldMetadata[fieldName].description });
		if (innerSchema && fieldSchema instanceof z.ZodOptional) fieldSchema.meta(fieldMetadata[fieldName]);
	}
	return schema;
}

//#endregion
export { createInsertSchema, createSelectSchema, registerFieldSchemas };