import type { Job } from './types';
import { join } from 'node:path';
import { readdir, mkdir, unlink } from 'node:fs/promises';
import { DATA_PATH } from '../data-path';

const QUEUE_DIR = join(DATA_PATH, 'queue', 'jobs');

export async function ensureQueueDir() {
  await mkdir(QUEUE_DIR, { recursive: true });
}

export async function readJob(id: string): Promise<Job | null> {
  const file = Bun.file(join(QUEUE_DIR, `${id}.json`));
  if (!(await file.exists())) return null;
  try {
    return await file.json();
  } catch {
    return null;
  }
}

export async function writeJob(job: Job): Promise<void> {
  await Bun.write(join(QUEUE_DIR, `${job.id}.json`), JSON.stringify(job, null, 2));
}

export async function listAllJobs(): Promise<Job[]> {
  try {
    const entries = await readdir(QUEUE_DIR);
    const jobs: Job[] = [];
    for (const entry of entries) {
      if (!entry.endsWith('.json')) continue;
      const file = Bun.file(join(QUEUE_DIR, entry));
      try {
        jobs.push(await file.json());
      } catch {
        // corrupted file — skip
      }
    }
    return jobs.sort((a, b) => b.createdAt - a.createdAt);
  } catch {
    return [];
  }
}

export async function deleteJobFile(id: string): Promise<void> {
  try {
    await unlink(join(QUEUE_DIR, `${id}.json`));
  } catch {
    // file doesn't exist — fine
  }
}
