import { requireV3X402Release } from '../x402/_lib/release';
import { assertV3ContractCatalog, V3_CONTRACT_CATALOG } from '../_lib/contracts';
import { assertV3ApiRouteInventory, V3_API_ROUTES } from '../_lib/inventory';
import { staticV3Json, V3_PROTOCOL_VERSION, V3_SCHEMA_VERSION } from '../_lib/http';

export function createV3ContractCatalogDocument(now = new Date()) {
  return {
    schema: 'vaultfire.v3.contract-catalog.v1',
    schemaVersion: V3_SCHEMA_VERSION,
    protocolVersion: V3_PROTOCOL_VERSION,
    route: '/api/v3/contracts',
    generatedAt: now.toISOString(),
    deploymentState: 'unconfigured',
    addressPolicy: 'null-until-independently-verified',
    contracts: V3_CONTRACT_CATALOG,
    routeInventory: V3_API_ROUTES,
  } as const;
}

export function assertV3ContractCatalogDocument(value: unknown): void {
  const body = value as Record<string, any>;
  if (
    !body || body.schema !== 'vaultfire.v3.contract-catalog.v1' ||
    body.schemaVersion !== V3_SCHEMA_VERSION || body.protocolVersion !== V3_PROTOCOL_VERSION ||
    body.route !== '/api/v3/contracts' || body.deploymentState !== 'unconfigured' ||
    body.addressPolicy !== 'null-until-independently-verified' ||
    Number.isNaN(Date.parse(body.generatedAt))
  ) throw new Error('invalid V3 contract catalog document');
  assertV3ContractCatalog(body.contracts);
  assertV3ApiRouteInventory(body.routeInventory);
}

export function GET(): Response {
  const closed = requireV3X402Release();
  if (closed) return closed;
  return staticV3Json(createV3ContractCatalogDocument(), assertV3ContractCatalogDocument);
}
