import { eq, desc } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { contentJobs } from "@paperclipai/db";

export function contentJobStore(db: Db) {
  return {
    create: (
      companyId: string,
      data: { jobType: string; input: Record<string, unknown>; sourceTaskId: string | null },
    ) =>
      db
        .insert(contentJobs)
        .values({ companyId, ...data })
        .returning()
        .then((r) => r[0]),

    getById: (id: string) =>
      db
        .select()
        .from(contentJobs)
        .where(eq(contentJobs.id, id))
        .then((r) => r[0] ?? null),

    listByCompany: (companyId: string) =>
      db
        .select()
        .from(contentJobs)
        .where(eq(contentJobs.companyId, companyId))
        .orderBy(desc(contentJobs.createdAt)),

    transition: (id: string, patch: Partial<typeof contentJobs.$inferInsert>) =>
      db
        .update(contentJobs)
        .set({ ...patch, updatedAt: new Date() })
        .where(eq(contentJobs.id, id)),
  };
}
