import { getCollection } from '../../lib/datastore.js';
import { NotFoundError } from '../../lib/errors.js';
import type { JobDefinitionDoc, JobRunDoc } from './types.js';

function defsCollection() {
  return getCollection<JobDefinitionDoc>('job_definitions', '/productId');
}

function runsCollection() {
  return getCollection<JobRunDoc>('job_runs', '/pk');
}

// ── Job Definition CRUD ──────────────────────────────────────

export async function listJobDefinitions(productId: string): Promise<JobDefinitionDoc[]> {
  return defsCollection().findMany({
    filter: { productId },
    sort: { name: 1 },
  });
}

export async function getJobDefinition(id: string, productId: string): Promise<JobDefinitionDoc> {
  const doc = await defsCollection().findById(id, productId);
  if (!doc) throw new NotFoundError(`Job definition '${id}' not found`);
  return doc;
}

export async function upsertJobDefinition(doc: JobDefinitionDoc): Promise<JobDefinitionDoc> {
  return defsCollection().upsert(doc);
}

export async function updateJobDefinition(
  id: string,
  productId: string,
  updates: Partial<JobDefinitionDoc>
): Promise<JobDefinitionDoc> {
  return defsCollection().update(id, productId, {
    ...updates,
    updatedAt: new Date().toISOString(),
  });
}

// ── Job Run CRUD ─────────────────────────────────────────────

export async function createJobRun(doc: JobRunDoc): Promise<JobRunDoc> {
  return runsCollection().create(doc);
}

export async function updateJobRun(doc: JobRunDoc): Promise<JobRunDoc> {
  return runsCollection().upsert(doc);
}

export async function listJobRuns(
  productId: string,
  jobName: string,
  limit = 20
): Promise<JobRunDoc[]> {
  return runsCollection().findMany({
    filter: { productId, jobName },
    sort: { startedAt: -1 },
    limit,
  });
}
