import { Type } from "@sinclair/typebox";

import type { CheckerSchemas } from "../types";

import {
  createAuthoringContentExpectationsSchema,
  createAuthoringFieldSchema,
  createAuthoringKeyedExpectationsSchema,
  createAuthoringStringMapSchema,
  createAuthoringValueExpectationSchema,
  createNormalizedContentExpectationsSchema,
  createNormalizedKeyedExpectationsSchema,
  createNormalizedValueExpectationSchema,
  httpMethodSchema,
  sizeSchema,
  statusCodePatternSchema,
  stringMapSchema,
} from "../../schema/fragments";

export const httpCheckerSchemas: CheckerSchemas = {
  authoring: {
    config: createHttpConfigSchema("authoring"),
    expect: createHttpExpectSchema("authoring"),
  },
  normalized: {
    config: createHttpConfigSchema("normalized"),
    expect: createHttpExpectSchema("normalized"),
  },
};

function createHttpConfigSchema(kind: "authoring" | "normalized") {
  const bool = Type.Boolean();
  const redirects = Type.Integer({ minimum: 0 });
  return Type.Object(
    {
      body: Type.Optional(Type.String()),
      headers: Type.Optional(kind === "authoring" ? createAuthoringStringMapSchema() : stringMapSchema),
      ignoreSSL: Type.Optional(kind === "authoring" ? createAuthoringFieldSchema(bool) : bool),
      maxBodyBytes: Type.Optional(sizeSchema),
      maxRedirects: Type.Optional(kind === "authoring" ? createAuthoringFieldSchema(redirects) : redirects),
      method: Type.Optional(kind === "authoring" ? createAuthoringFieldSchema(httpMethodSchema) : httpMethodSchema),
      url: Type.String({ minLength: 1 }),
    },
    { additionalProperties: false },
  );
}

function createHttpExpectSchema(kind: "authoring" | "normalized") {
  return Type.Object(
    {
      body: Type.Optional(
        kind === "authoring" ? createAuthoringContentExpectationsSchema() : createNormalizedContentExpectationsSchema(),
      ),
      durationMs: Type.Optional(
        kind === "authoring" ? createAuthoringValueExpectationSchema() : createNormalizedValueExpectationSchema(),
      ),
      headers: Type.Optional(
        kind === "authoring" ? createAuthoringKeyedExpectationsSchema() : createNormalizedKeyedExpectationsSchema(),
      ),
      status: Type.Optional(Type.Array(statusCodePatternSchema)),
    },
    { additionalProperties: false },
  );
}
