/**
 * Bootstrap the `plaintext` SecretBackend + backfill existing Secret rows.
 *
 * Runs on every mcpd startup. Idempotent:
 *   - if no SecretBackend exists, create `default` (type `plaintext`, isDefault=true)
 *   - if any Secret has no backendId (fresh after schema migration), point it at `default`
 *   - if no backend is currently flagged default, promote `default`
 *
 * Safe to run repeatedly; never destroys configuration.
 */
import type { PrismaClient } from '@prisma/client';

/** Well-known name for the always-present plaintext backend. */
export const DEFAULT_PLAINTEXT_BACKEND_NAME = 'default';

export async function bootstrapSecretBackends(prisma: PrismaClient): Promise<void> {
  let plaintext = await prisma.secretBackend.findUnique({
    where: { name: DEFAULT_PLAINTEXT_BACKEND_NAME },
  });

  if (plaintext === null) {
    plaintext = await prisma.secretBackend.create({
      data: {
        name: DEFAULT_PLAINTEXT_BACKEND_NAME,
        type: 'plaintext',
        isDefault: true,
        description: 'Default in-database plaintext backend. Seeded on first startup.',
      },
    });
  }

  const currentDefault = await prisma.secretBackend.findFirst({ where: { isDefault: true } });
  if (currentDefault === null) {
    await prisma.secretBackend.update({
      where: { id: plaintext.id },
      data: { isDefault: true },
    });
  }

  // Backfill any secrets left with an empty backendId after the schema migration.
  // `findMany({ where: { backendId: '' } })` catches rows that existed before
  // the column was added and had a default-empty value assigned.
  const orphans = await prisma.secret.findMany({
    where: { backendId: '' },
    select: { id: true },
  });
  if (orphans.length > 0) {
    await prisma.secret.updateMany({
      where: { id: { in: orphans.map((o) => o.id) } },
      data: { backendId: plaintext.id },
    });
  }
}
