import { prisma } from "../lib/db";
import { createLogger } from "../lib/logger";
import { reconcileWebhook } from "./gitea";

const log = createLogger("WEBHOOK_RECONCILE");

// On boot, bring every PP-managed Gitea webhook up to the current standard so
// existing installs self-heal without the operator having to disable/re-enable
// each repo. Chiefly backfills the "pull_request_sync" event (added after these
// webhooks were first registered — without it pushes to a PR branch never
// redeploy) and names any webhook left unnamed. Errors are per-repo so one bad
// PAT or deleted repo can't abort the whole pass.
export async function runWebhookReconciliation() {
  log.info("Reconciling Gitea webhooks");

  const configs = await prisma.repoConfig.findMany({
    where: { isEnabled: true, giteaWebhookId: { not: null } },
    include: { user: true },
  });

  let patched = 0;
  let named = 0;
  let missing = 0;

  for (const config of configs) {
    const { user, repoOwner, repoName, giteaWebhookId } = config;
    if (!user?.giteaInstanceUrl || !user?.giteaPAT || !giteaWebhookId) continue;

    try {
      const result = await reconcileWebhook(user as any, repoOwner, repoName, giteaWebhookId);
      if (result.status === "missing") {
        missing++;
        log.warn({ repo: `${repoOwner}/${repoName}`, giteaWebhookId }, "Webhook no longer exists in Gitea");
      } else if (result.status === "patched") {
        patched++;
        if (result.named) named++;
        log.info(
          { repo: `${repoOwner}/${repoName}`, addedEvents: result.addedEvents, named: result.named, reactivated: result.reactivated },
          "Webhook reconciled",
        );
      }
    } catch (e) {
      log.warn({ e, repo: `${repoOwner}/${repoName}`, userId: user.id }, "Failed to reconcile webhook");
    }
  }

  log.info({ total: configs.length, patched, named, missing }, "Webhook reconciliation complete");
}
