import path from "path";
import fs from "fs/promises";
import config from "../config/index.js";
import logger from "../utils/logger.js";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const DATA_DIR = path.dirname(config.database.path);
const DB_PATH = path.resolve(config.database.path);

async function ensureDatabase() {
  try {
    await fs.mkdir(DATA_DIR, { recursive: true });
    try {
      await fs.access(DB_PATH);
      logger.info(`Database file exists at: ${DB_PATH}`);
    } catch {
      const initial = { jobs: [] };
      await fs.writeFile(DB_PATH, JSON.stringify(initial, null, 2), "utf-8");
      logger.info(`Database file created at: ${DB_PATH}`);
    }
  } catch (error) {
    logger.error("Failed to initialize database:", error);
    throw error;
  }
}

async function readDb() {
  try {
    const raw = await fs.readFile(DB_PATH, "utf-8");
    return JSON.parse(raw);
  } catch (error) {
    logger.error("Failed to read database:", error);
    throw new Error("Database read error");
  }
}

async function writeDb(data) {
  try {
    await fs.writeFile(DB_PATH, JSON.stringify(data, null, 2), "utf-8");
  } catch (error) {
    logger.error("Failed to write database:", error);
    throw new Error("Database write error");
  }
}

export { ensureDatabase, readDb, writeDb };


