import { getV3Contract } from '../../_lib/contracts';
import { invalidV3Input, staticV3Json, V3_CONTRACT_NAME, V3_PROTOCOL_VERSION, V3_SCHEMA_VERSION } from '../../_lib/http';
import { requireV3X402Release } from '../../x402/_lib/release';

export async function GET(
  _request: Request,
  context: { params: Promise<{ name: string }> | { name: string } },
): Promise<Response> {
  const closed = requireV3X402Release();
  if (closed) return closed;
  const { name } = await context.params;
  if (!V3_CONTRACT_NAME.test(name)) return invalidV3Input('invalid_contract_name', 'Contract name is not canonical');
  const contract = getV3Contract(name);
  if (!contract) {
    return Response.json({
      schema: 'vaultfire.v3.contract-result.v1',
      schemaVersion: V3_SCHEMA_VERSION,
      protocolVersion: V3_PROTOCOL_VERSION,
      route: '/api/v3/contracts/:name',
      name,
      data: null,
      error: { code: 'v3_contract_not_in_catalog', message: 'Contract is not in the canonical V3 catalog', retryable: false },
    }, { status: 404, headers: { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' } });
  }
  const body = {
    schema: 'vaultfire.v3.contract-result.v1',
    schemaVersion: V3_SCHEMA_VERSION,
    protocolVersion: V3_PROTOCOL_VERSION,
    route: '/api/v3/contracts/:name',
    name: contract.name,
    data: contract,
  };
  return staticV3Json(body, (value) => {
    const candidate = value as typeof body;
    if (candidate.schema !== body.schema || candidate.data.address !== null ||
        candidate.data.executableEvidenceAvailable !== false) throw new Error('invalid V3 contract result');
  });
}
