import { env } from '../../config/env';

/**
 * GitHub Actions client for the website rebuild (docs/blog-cms-plan.md, B2).
 *
 * The website is static HTML built by hostelcare-website's deploy workflow,
 * so publishing a post changes nothing until that workflow runs. This asks
 * GitHub to run it (workflow_dispatch on BLOG_GITHUB_REF) and reads the run
 * back, so the editor sees "building → live".
 *
 * workflow_dispatch answers 204 with no run id, so the run is found by
 * listing dispatch runs created at or after the request. Everything goes
 * through `github` so the tests can stand in for GitHub.
 */

export interface GithubRun {
  id: number;
  status: string;
  conclusion: string | null;
  html_url: string;
  created_at: string;
}

export const isGithubConfigured = () => Boolean(env.BLOG_GITHUB_TOKEN);

async function call<T>(method: string, path: string, body?: unknown): Promise<T | null> {
  if (!env.BLOG_GITHUB_TOKEN) {
    const err = new Error('GitHub is not set up on this server (BLOG_GITHUB_TOKEN), so the website will rebuild once it is.');
    (err as Error & { code?: string }).code = 'GITHUB_NOT_CONFIGURED';
    throw err;
  }
  const res = await fetch(`https://api.github.com${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${env.BLOG_GITHUB_TOKEN}`,
      Accept: 'application/vnd.github+json',
      'X-GitHub-Api-Version': '2022-11-28',
      'User-Agent': 'hostelcare-blog-cms',
      ...(body ? { 'Content-Type': 'application/json' } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(15_000),
  });
  if (res.status === 204) return null;
  const text = await res.text();
  let json: { message?: string } | null = null;
  try {
    json = text ? JSON.parse(text) : null;
  } catch {
    json = null;
  }
  if (!res.ok) throw new Error(`GitHub ${res.status}: ${json?.message ?? (text.slice(0, 120) || res.statusText)}`);
  return json as T;
}

const repo = () => env.BLOG_GITHUB_REPO;
const workflow = () => encodeURIComponent(env.BLOG_GITHUB_WORKFLOW);

export const github = {
  async dispatch(): Promise<void> {
    await call('POST', `/repos/${repo()}/actions/workflows/${workflow()}/dispatches`, { ref: env.BLOG_GITHUB_REF });
  },
  async listDispatchRuns(): Promise<GithubRun[]> {
    const json = await call<{ workflow_runs: GithubRun[] }>('GET', `/repos/${repo()}/actions/workflows/${workflow()}/runs?event=workflow_dispatch&per_page=10`);
    return json?.workflow_runs ?? [];
  },
  async getRun(runId: bigint | number): Promise<GithubRun | null> {
    return call<GithubRun>('GET', `/repos/${repo()}/actions/runs/${runId}`);
  },
};

/** The run started for a dispatch sent at `since`: the first one at or after it. */
export async function findRunSince(since: Date): Promise<GithubRun | null> {
  const from = since.getTime() - 5_000; // GitHub's clock against ours
  const runs = await github.listDispatchRuns();
  return (
    runs
      .filter((r) => new Date(r.created_at).getTime() >= from)
      .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime())[0] ?? null
  );
}

/** A GitHub run → our build state. */
export function stateOfRun(run: GithubRun): 'BUILDING' | 'LIVE' | 'FAILED' {
  if (run.status !== 'completed') return 'BUILDING';
  return run.conclusion === 'success' ? 'LIVE' : 'FAILED';
}
