import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import postgres from "postgres";

const databaseUrl = process.env.AWP_TEST_POSTGRES_URL;
const repository = process.env.AWP_PROJECT_REPOSITORY;
const repositoryUrl = process.env.AWP_SELF_REPOSITORY_URL;
if (!databaseUrl) throw new Error("AWP_TEST_POSTGRES_URL is required");
if (!repository) throw new Error("AWP_PROJECT_REPOSITORY is required");
if (!repositoryUrl) throw new Error("AWP_SELF_REPOSITORY_URL is required");

const sql = postgres(databaseUrl, { max: 1 });
try {
  const [change] = await sql<{ change_set_id: string; factory_run_id: string }[]>`
    select cs.id as change_set_id, fr.id as factory_run_id
    from change_sets cs
    join projects p on p.id = cs.project_id
    join factory_runs fr on fr.task_id = cs.task_id
    where p.repository_url = ${repositoryUrl}
      and cs.status = 'merged'
    order by cs.created_at desc
    limit 1
  `;
  assert.ok(change, "a merged AWP self-project ChangeSet must exist");
  const commitOutput = execFileSync(
    "git",
    [
      "log",
      "main",
      "-1",
      "--fixed-strings",
      `--grep=AWP-ChangeSet: ${change.change_set_id}`,
      "--format=%H%n%cn <%ce>%n%B",
    ],
    { cwd: repository, encoding: "utf8" },
  ).trim();
  const [commitSha, committer, ...bodyLines] = commitOutput.split("\n");
  assert.ok(commitSha, "the merged self ChangeSet commit must exist on main");
  assert.equal(committer, "AWP Control Plane <control-plane@awp.local>");
  const body = bodyLines.join("\n");
  assert.match(body, new RegExp(`^AWP-FactoryRun: ${change.factory_run_id}$`, "m"));
  assert.match(body, new RegExp(`^AWP-ChangeSet: ${change.change_set_id}$`, "m"));
  process.stdout.write(
    `AC-29 PASS: AWP FactoryRun ${change.factory_run_id} authored self change ${commitSha} merged by the control plane\n`,
  );
} finally {
  await sql.end({ timeout: 5 });
}
