import { randomUUID } from "node:crypto";
import { execute, json, one, pool, query, type Db, type Row } from "../db/db.js";

export interface JobResult { message: string; href?: string }
export interface Job { id: string; projectId: string | null; userId: string | null; payload: Row; progress(pct: number, note: string): Promise<void> }
const handlers = new Map<string, (job: Job) => Promise<JobResult | void>>();
export const defineJob = (type: string, run: (job: Job) => Promise<JobResult | void>) => { handlers.set(type, run); };

export async function enqueue(db: Db, type: string, payload: Row, o: { projectId?: string; userId?: string; delaySeconds?: number; dedupe?: string } = {}): Promise<string> {
  if (o.dedupe) { const old = await one(db, "SELECT id FROM jobs WHERE dedupe_key=?", [o.dedupe]); if (old) return String(old["id"]); }
  const r = await execute(db, "INSERT INTO jobs (queue, type, payload, dedupe_key, status, run_at, requested_by, project_id) VALUES ('default',?,?,?,'queued',UTC_TIMESTAMP(3) + INTERVAL ? SECOND,?,?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)",
    [type, JSON.stringify(payload), o.dedupe ?? null, o.delaySeconds ?? 0, o.userId ?? null, o.projectId ?? null]);
  return String(r.insertId);
}
/** Claims one job with a plain UPDATE, which works on every MySQL and MariaDB version and is safe with several workers. */
export async function runNextJob(): Promise<boolean> {
  const me = randomUUID();
  const claimed = await execute(pool, `UPDATE jobs SET status='running', locked_by=?, locked_until=UTC_TIMESTAMP(3)+INTERVAL 5 MINUTE, attempts=attempts+1
    WHERE (status='queued' OR (status='running' AND locked_until<UTC_TIMESTAMP(3))) AND run_at<=UTC_TIMESTAMP(3) ORDER BY run_at LIMIT 1`, [me]);
  if (!claimed.affectedRows) return false;
  const j = (await one(pool, "SELECT * FROM jobs WHERE locked_by=?", [me]))!;
  const jobId = String(j["id"]);
  // The key is released as soon as work starts, so a change made during the run schedules another run.
  await execute(pool, "UPDATE jobs SET dedupe_key=NULL WHERE id=?", [jobId]);
  const run = handlers.get(j["type"] as string);
  try {
    if (!run) throw new Error(`No handler for job type ${j["type"]}`);
    const result = await run({ id: jobId, projectId: j["project_id"] as string | null, userId: j["requested_by"] as string | null, payload: json<Row>(j["payload"], {}),
      progress: async (pct, note) => { await execute(pool, "UPDATE jobs SET progress_pct=?, progress_note=?, locked_until=UTC_TIMESTAMP(3)+INTERVAL 5 MINUTE WHERE id=?", [pct, note.slice(0, 190), jobId]); } });
    await execute(pool, "UPDATE jobs SET status='done', progress_pct=100, result_json=?, finished_at=UTC_TIMESTAMP(3), last_error=NULL WHERE id=?", [JSON.stringify(result ?? { message: "Done." }), jobId]);
  } catch (error) {
    const dead = !run || (error as { status?: number }).status !== undefined || Number(j["attempts"]) >= Number(j["max_attempts"]);
    await execute(pool, "UPDATE jobs SET status=?, last_error=?, run_at=UTC_TIMESTAMP(3)+INTERVAL ? SECOND, finished_at=IF(?,UTC_TIMESTAMP(3),NULL) WHERE id=?", [dead ? "failed" : "queued", String((error as Error).message).slice(0, 900), 30 * 2 ** Number(j["attempts"]), dead, jobId]);
  }
  return true;
}
export const getJob = (projectId: string, jobId: string) => one(pool, "SELECT * FROM jobs WHERE id=? AND project_id=?", [jobId, projectId]);
/** One instance at a time may run the schedule. */
export async function holdLease(name: string, holder: string, seconds: number): Promise<boolean> {
  await execute(pool, "INSERT INTO scheduler_leases (name, holder, expires_at) VALUES (?,?,UTC_TIMESTAMP(3)+INTERVAL ? SECOND) ON DUPLICATE KEY UPDATE holder=IF(expires_at<UTC_TIMESTAMP(3) OR holder=VALUES(holder), VALUES(holder), holder), expires_at=IF(holder=VALUES(holder), VALUES(expires_at), expires_at)", [name, holder, seconds]);
  return (await one(pool, "SELECT holder FROM scheduler_leases WHERE name=?", [name]))?.["holder"] === holder;
}
export const projectIds = async () => (await query(pool, "SELECT id FROM projects")).map((p) => String(p["id"]));
