import { goals, projects, type Db } from "@peppa/db"; import { and, asc, eq, or } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; export type Project = typeof projects.$inferSelect; export type Goal = typeof goals.$inferSelect; export interface NewProject { slug: string; key: string; name: string; description?: string; giteaOwner: string; giteaRepo?: string; workspacePath: string; ownerId?: number | null; } export async function createProject(db: Db, p: NewProject): Promise { const key = p.key.toUpperCase(); if (!/^[A-Z][A-Z0-9]{1,9}$/.test(key)) throw new PeppaError(`Invalid project key "${p.key}": 2–10 chars, A–Z/0–9, starts with a letter`); if (!/^[a-z0-9][a-z0-9-]*$/.test(p.slug)) throw new PeppaError(`Invalid slug "${p.slug}": lowercase letters, digits, dashes`); const [row] = await db .insert(projects) .values({ ...p, key, giteaRepo: p.giteaRepo ?? p.slug }) .returning(); return row!; } export async function listProjects(db: Db): Promise { return db.select().from(projects).orderBy(asc(projects.key)); } /** Finds a project by task key prefix ("PEP") or slug ("peppa"). */ export async function getProject(db: Db, keyOrSlug: string): Promise { const [row] = await db .select() .from(projects) .where(or(eq(projects.key, keyOrSlug.toUpperCase()), eq(projects.slug, keyOrSlug.toLowerCase()))); if (!row) throw new PeppaError(`Project "${keyOrSlug}" not found`); return row; } export async function createGoal(db: Db, projectId: number, title: string, description?: string): Promise { const [row] = await db.insert(goals).values({ projectId, title, description }).returning(); return row!; } export async function listGoals(db: Db, projectId: number, includeClosed = false): Promise { return db .select() .from(goals) .where(includeClosed ? eq(goals.projectId, projectId) : and(eq(goals.projectId, projectId), eq(goals.status, "open"))) .orderBy(asc(goals.id)); } export async function getGoal(db: Db, projectId: number, goalId: number): Promise { const [row] = await db.select().from(goals).where(and(eq(goals.id, goalId), eq(goals.projectId, projectId))); if (!row) throw new PeppaError(`Goal #${goalId} not found in this project`); return row; } export interface GoalPatch { title?: string; description?: string | null; status?: Goal["status"]; } export async function updateGoal(db: Db, projectId: number, goalId: number, patch: GoalPatch): Promise { await getGoal(db, projectId, goalId); const [row] = await db.update(goals).set(patch).where(and(eq(goals.id, goalId), eq(goals.projectId, projectId))).returning(); return row!; }