/**
 * Zod schemas for page-layout API endpoints.
 *
 * layoutBodySchema runs superRefine to validate each module's config against
 * the registered MODULE_REGISTRY[type].configSchema — unknown types and
 * invalid configs both produce 'custom' issues.
 */

import { z } from 'zod';
import { MODULE_REGISTRY } from '@/server/page-layout/registry';

const moduleVisibility = z.object({ guests: z.boolean(), loggedIn: z.boolean() });

const layoutModuleSchema = z
  .object({
    instanceId: z.uuid(),
    type: z.string(),
    config: z.unknown(),
    visibility: moduleVisibility,
  })
  .superRefine((val, ctx) => {
    const def = MODULE_REGISTRY[val.type];
    if (!def) {
      ctx.addIssue({ code: 'custom', message: `Unknown module type: ${val.type}` });
      return;
    }
    const inner = def.configSchema.safeParse(val.config);
    if (!inner.success) {
      ctx.addIssue({
        code: 'custom',
        message: `Invalid config for ${val.type}: ${inner.error.message}`,
      });
    }
  });

export const layoutBodySchema = z.object({
  mobile: z.array(layoutModuleSchema),
  desktop: z.array(layoutModuleSchema),
});

export const putDraftBody = z.object({
  body: layoutBodySchema,
  updatedAt: z.iso.datetime().nullable(),
});

export const publishBody = z.object({ note: z.string().max(500).optional() });
export const scheduleBody = z.object({ versionId: z.uuid(), at: z.iso.datetime() });
export const revertBody = z.object({
  versionId: z.uuid(),
  note: z.string().max(500).optional(),
});
