import { BlogBuildState, type BlogBuild } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { findRunSince, github, isGithubConfigured, stateOfRun } from './blog-github';

/**
 * Website rebuilds (docs/blog-cms-plan.md, B2).
 *
 * One PENDING build at a time: every change that needs the site rebuilt joins
 * it, so five publishes in a minute make one deploy. Nothing is sent while
 * another build is QUEUED or BUILDING; the job sends the pending one when that
 * finishes. Until BLOG_GITHUB_TOKEN is set a build just waits.
 */

const OPEN: BlogBuildState[] = [BlogBuildState.QUEUED, BlogBuildState.BUILDING];
/** GitHub took the request but no run appeared: give up so the next change can try. */
const NO_RUN_AFTER_MS = 10 * 60_000;

const errText = (err: unknown) => (err instanceof Error ? err.message : String(err)).slice(0, 300);

/** Note that the site needs rebuilding, and try to send it now. */
export async function requestBuild(input: { userId?: string | null; reason: string }): Promise<BlogBuild> {
  const build =
    (await db.blogBuild.findFirst({ where: { state: BlogBuildState.PENDING }, orderBy: { createdAt: 'asc' } })) ??
    (await db.blogBuild.create({ data: { state: BlogBuildState.PENDING, reason: input.reason.slice(0, 300), requestedById: input.userId ?? null } }));
  await dispatchPending();
  return build;
}

/** Send the waiting build to GitHub, unless one is already running. */
export async function dispatchPending(): Promise<void> {
  const pending = await db.blogBuild.findFirst({ where: { state: BlogBuildState.PENDING }, orderBy: { createdAt: 'asc' } });
  if (!pending) return;
  if (!isGithubConfigured()) {
    await db.blogBuild.update({ where: { id: pending.id }, data: { lastError: 'Waiting: GitHub is not set up on the server yet (BLOG_GITHUB_TOKEN).' } });
    return;
  }
  if (await db.blogBuild.count({ where: { state: { in: OPEN } } })) return;
  const at = new Date();
  try {
    await github.dispatch();
    await db.blogBuild.update({ where: { id: pending.id }, data: { state: BlogBuildState.QUEUED, dispatchedAt: at, attempts: { increment: 1 }, lastError: null } });
  } catch (err) {
    // Stays pending; the job tries again next minute.
    await db.blogBuild.update({ where: { id: pending.id }, data: { attempts: { increment: 1 }, lastError: errText(err) } });
  }
}

/** Follow sent builds to LIVE or FAILED, then send whatever is waiting. */
export async function pollBuilds(): Promise<void> {
  const open = await db.blogBuild.findMany({ where: { state: { in: OPEN } }, orderBy: { createdAt: 'asc' } });
  for (const b of open) {
    try {
      const run = b.runId ? await github.getRun(b.runId) : await findRunSince(b.dispatchedAt ?? b.createdAt);
      if (!run) {
        if (Date.now() - (b.dispatchedAt ?? b.createdAt).getTime() > NO_RUN_AFTER_MS) {
          await db.blogBuild.update({ where: { id: b.id }, data: { state: BlogBuildState.FAILED, lastError: 'GitHub took the request but no build started.', finishedAt: new Date() } });
        }
        continue;
      }
      const state = stateOfRun(run);
      const done = state !== BlogBuildState.BUILDING;
      await db.blogBuild.update({
        where: { id: b.id },
        data: {
          runId: BigInt(run.id),
          runUrl: run.html_url ?? null,
          state,
          ...(done ? { finishedAt: new Date(), lastError: state === BlogBuildState.FAILED ? `The website build ended: ${run.conclusion ?? 'failed'}.` : null } : {}),
        },
      });
    } catch (err) {
      await db.blogBuild.update({ where: { id: b.id }, data: { lastError: errText(err) } });
    }
  }
  await dispatchPending();
}

export function presentBuild(b: BlogBuild | null) {
  if (!b) return null;
  return {
    id: b.id,
    state: b.state,
    reason: b.reason,
    runUrl: b.runUrl,
    attempts: b.attempts,
    lastError: b.lastError,
    dispatchedAt: b.dispatchedAt,
    finishedAt: b.finishedAt,
    createdAt: b.createdAt,
    updatedAt: b.updatedAt,
  };
}

export async function latestBuild() {
  const b = await db.blogBuild.findFirst({ orderBy: { createdAt: 'desc' } });
  return { build: presentBuild(b), githubConfigured: isGithubConfigured() };
}

/**
 * "Try again": a new build, and every post whose last build failed moves to
 * it, so their "failed" clears when it goes live (GymCare bug 4).
 */
export async function retryBuild(userId: string) {
  const build = await requestBuild({ userId, reason: 'Tried again' });
  await db.blogPost.updateMany({ where: { lastBuild: { state: BlogBuildState.FAILED } }, data: { lastBuildId: build.id } });
  return latestBuild();
}
