/**
 * Validation utilities for Fastify
 */

import { FastifySchema } from 'fastify';
import { ZodSchema, ZodTypeAny } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';

/**
 * Convert Zod schema to Fastify JSON schema
 */
export function zodToFastifySchema(zodSchema: ZodSchema): FastifySchema {
  const jsonSchema = zodToJsonSchema(zodSchema, {
    target: 'openApi3',
  });

  return {
    body: jsonSchema as FastifySchema['body'],
  };
}

/**
 * Create Fastify schema from Zod schema for request body
 */
export function createBodySchema<T extends ZodTypeAny>(schema: T): FastifySchema {
  return zodToFastifySchema(schema);
}

/**
 * Create Fastify schema with body and response
 */
export function createSchema<TBody extends ZodTypeAny, TResponse extends ZodTypeAny>(
  bodySchema: TBody,
  responseSchema?: TResponse
): FastifySchema {
  const schema: FastifySchema = zodToFastifySchema(bodySchema);

  if (responseSchema) {
    schema.response = {
      200: zodToJsonSchema(responseSchema, { target: 'openApi3' }) as FastifySchema['response'],
    };
  }

  return schema;
}

