import { z } from "zod";
import { createClient, defineContract } from "../contracts/core";

export const ConnectorEndpointSchema = z.object({
  id: z.string(),
  method: z.string(),
  path: z.string(),
  operationId: z.string().nullable(),
  summary: z.string().nullable(),
  description: z.string().nullable(),
  tags: z.array(z.string()),
});

export const ConnectorSummarySchema = z.object({
  id: z.number(),
  name: z.string(),
  type: z.literal("openapi"),
  sourceUrl: z.string(),
  specVersion: z.string().nullable(),
  description: z.string().nullable(),
  endpointCount: z.number(),
  lastSyncedAt: z.date().nullable(),
  createdAt: z.date(),
  updatedAt: z.date(),
});

export const ConnectorSchema = ConnectorSummarySchema.extend({
  rawSpec: z.record(z.string(), z.unknown()).nullable(),
  endpoints: z.array(ConnectorEndpointSchema),
});

export const ConnectorIdParamsSchema = z.object({
  connectorId: z.number(),
});

export const ListConnectorsResponseSchema = z.object({
  connectors: z.array(ConnectorSummarySchema),
});

export const ImportOpenApiConnectorParamsSchema = z.object({
  url: z.string().url(),
  name: z.string().trim().min(1).optional(),
});

export const connectorContracts = {
  listConnectors: defineContract({
    channel: "connector:list",
    input: z.void(),
    output: ListConnectorsResponseSchema,
  }),

  getConnector: defineContract({
    channel: "connector:get",
    input: ConnectorIdParamsSchema,
    output: ConnectorSchema,
  }),

  importOpenApiConnector: defineContract({
    channel: "connector:import-openapi",
    input: ImportOpenApiConnectorParamsSchema,
    output: ConnectorSchema,
  }),

  refreshConnector: defineContract({
    channel: "connector:refresh",
    input: ConnectorIdParamsSchema,
    output: ConnectorSchema,
  }),

  deleteConnector: defineContract({
    channel: "connector:delete",
    input: ConnectorIdParamsSchema,
    output: z.void(),
  }),
} as const;

export const connectorClient = createClient(connectorContracts);

export type ConnectorEndpoint = z.infer<typeof ConnectorEndpointSchema>;
export type ConnectorSummary = z.infer<typeof ConnectorSummarySchema>;
export type Connector = z.infer<typeof ConnectorSchema>;
export type ImportOpenApiConnectorParams = z.infer<
  typeof ImportOpenApiConnectorParamsSchema
>;
