import { batch, first, stmt } from "../db";
import { randomId } from "../crypto";
import { forbidden } from "../errors";
import { allocateIssueNumber, indexIssue, issueUrl, setIssueState } from "../issues";
import type { IssueRow } from "../issues";
import { emitNotification, emitWebhook, recordActivity } from "../events/emit";
import type { RepoRow, Viewer } from "~/lib/types";
/** Mirrors the web issue form (src/fns/issues.ts createIssue) for an already-authorized caller. */
export async function insertIssue(repo: RepoRow, viewer: Viewer, title: string, body: string): Promise<number> {
if (repo.has_issues !== 1) throw forbidden("Issues are disabled for this repository");
const number = await allocateIssueNumber(repo.id);
const id = randomId();
const now = Date.now();
await batch([
stmt(
`INSERT INTO issues (id, repo_id, number, author_id, title, body, state, is_pull, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, 'open', 0, ?, ?)`,
id,
repo.id,
number,
viewer.id,
title,
body,
now,
now,
),
stmt("UPDATE repos SET open_issues_count = open_issues_count + 1 WHERE id = ?", repo.id),
]);
await indexIssue({ id, repo_id: repo.id, title, body });
await recordActivity(viewer.id, repo.id, "issue_opened", { number, title });
const url = issueUrl(repo, { number, is_pull: 0 });
await emitWebhook(repo.id, "issues", {
action: "opened",
issue: { number, title, body, html_url: url },
sender: { login: viewer.name, id: viewer.id },
});
await emitNotification({
repoId: repo.id,
issueId: id,