import { PrismaClient, Prisma } from '@prisma/client';

export interface TemplateEnvEntry {
  name: string;
  description?: string;
  required?: boolean;
  defaultValue?: string;
}

export interface HealthCheckSpec {
  /** When set, probe sends initialize + tools/call (readiness). When omitted, probe sends tools/list only (liveness). */
  tool?: string;
  arguments?: Record<string, unknown>;
  intervalSeconds?: number;
  timeoutSeconds?: number;
  failureThreshold?: number;
}

export interface SeedTemplate {
  name: string;
  version: string;
  description: string;
  packageName?: string;
  dockerImage?: string;
  transport: 'STDIO' | 'SSE' | 'STREAMABLE_HTTP';
  repositoryUrl?: string;
  externalUrl?: string;
  command?: string[];
  containerPort?: number;
  replicas?: number;
  env?: TemplateEnvEntry[];
  healthCheck?: HealthCheckSpec;
}

export async function seedTemplates(
  prisma: PrismaClient,
  templates: SeedTemplate[],
): Promise<number> {
  let upserted = 0;

  for (const tpl of templates) {
    await prisma.mcpTemplate.upsert({
      where: { name: tpl.name },
      update: {
        version: tpl.version,
        description: tpl.description,
        packageName: tpl.packageName ?? null,
        dockerImage: tpl.dockerImage ?? null,
        transport: tpl.transport,
        repositoryUrl: tpl.repositoryUrl ?? null,
        externalUrl: tpl.externalUrl ?? null,
        command: (tpl.command ?? Prisma.JsonNull) as Prisma.InputJsonValue,
        containerPort: tpl.containerPort ?? null,
        replicas: tpl.replicas ?? 1,
        env: (tpl.env ?? []) as unknown as Prisma.InputJsonValue,
        healthCheck: (tpl.healthCheck ?? Prisma.JsonNull) as unknown as Prisma.InputJsonValue,
      },
      create: {
        name: tpl.name,
        version: tpl.version,
        description: tpl.description,
        packageName: tpl.packageName ?? null,
        dockerImage: tpl.dockerImage ?? null,
        transport: tpl.transport,
        repositoryUrl: tpl.repositoryUrl ?? null,
        externalUrl: tpl.externalUrl ?? null,
        command: (tpl.command ?? Prisma.JsonNull) as Prisma.InputJsonValue,
        containerPort: tpl.containerPort ?? null,
        replicas: tpl.replicas ?? 1,
        env: (tpl.env ?? []) as unknown as Prisma.InputJsonValue,
        healthCheck: (tpl.healthCheck ?? Prisma.JsonNull) as unknown as Prisma.InputJsonValue,
      },
    });
    upserted++;
  }

  return upserted;
}
