import type { Context } from "hono";
import type { ContentfulStatusCode } from "hono/utils/http-status";

export type ApiError = {
	error: {
		code: string;
		message: string;
		field?: string;
	};
};

export function errorBody(
	code: string,
	message: string,
	field?: string,
): ApiError {
	return field
		? { error: { code, message, field } }
		: { error: { code, message } };
}

export function jsonError(
	c: Context,
	status: ContentfulStatusCode,
	code: string,
	message: string,
	field?: string,
) {
	return c.json(errorBody(code, message, field), status);
}

/** Forme `steps[2].options[0].next` (section 5.2). */
export function zodField(path: PropertyKey[]): string | undefined {
	if (path.length === 0) return undefined;
	let field = "";
	for (const key of path) {
		if (typeof key === "number") {
			field += `[${key}]`;
			continue;
		}
		field += field.length === 0 ? String(key) : `.${String(key)}`;
	}
	return field;
}

const uuidPattern =
	/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export function parseUuid(value: string): string | undefined {
	return uuidPattern.test(value) ? value : undefined;
}
