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

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

import {
  createAuthoringContentExpectationsSchema,
  createAuthoringFieldSchema,
  createAuthoringValueExpectationSchema,
  createNormalizedContentExpectationsSchema,
  createNormalizedValueExpectationSchema,
  sizeSchema,
} from "../../schema/fragments";

export const tcpCheckerSchemas: CheckerSchemas = {
  authoring: {
    config: createTcpConfigSchema("authoring"),
    expect: createTcpExpectSchema("authoring"),
  },
  normalized: {
    config: createTcpConfigSchema("normalized"),
    expect: createTcpExpectSchema("normalized"),
  },
};

function createTcpConfigSchema(kind: "authoring" | "normalized") {
  const port = Type.Integer({ maximum: 65535, minimum: 1 });
  const readBanner = Type.Boolean();
  return Type.Object(
    {
      bannerReadTimeout: Type.Optional(Type.Number({ minimum: 0 })),
      host: Type.String({ minLength: 1 }),
      maxBannerBytes: Type.Optional(sizeSchema),
      port: kind === "authoring" ? createAuthoringFieldSchema(port) : port,
      readBanner: Type.Optional(kind === "authoring" ? createAuthoringFieldSchema(readBanner) : readBanner),
    },
    { additionalProperties: false },
  );
}

function createTcpExpectSchema(kind: "authoring" | "normalized") {
  const connected = Type.Boolean();
  return Type.Object(
    {
      banner: Type.Optional(
        kind === "authoring" ? createAuthoringContentExpectationsSchema() : createNormalizedContentExpectationsSchema(),
      ),
      connected: Type.Optional(kind === "authoring" ? createAuthoringFieldSchema(connected) : connected),
      durationMs: Type.Optional(
        kind === "authoring" ? createAuthoringValueExpectationSchema() : createNormalizedValueExpectationSchema(),
      ),
    },
    { additionalProperties: false },
  );
}
