import { JobModel } from "../models/job.model.js";
import logger from "../utils/logger.js";

export async function listJobs(filters = {}) {
  try {
    const query = {};
    
    if (filters.status) {
      query.status = filters.status;
    }
    
    const items = await JobModel.find(query).sort({ createdAt: -1 }).lean();
    return items;
  } catch (error) {
    logger.error("Error in listJobs service:", error);
    throw error;
  }
}

export async function getJobById(id) {
  try {
    if (!id) {
      throw new Error("Job ID is required");
    }
    const item = await JobModel.findById(id).lean();
    return item || null;
  } catch (error) {
    logger.error("Error in getJobById service:", error);
    throw error;
  }
}

export async function createJob(data) {
  try {
    const created = await JobModel.create(data);
    return created.toObject();
  } catch (error) {
    logger.error("Error in createJob service:", error);
    throw error;
  }
}

export async function updateJob(id, data) {
  try {
    if (!id) {
      throw new Error("Job ID is required");
    }
    const updated = await JobModel.findByIdAndUpdate(id, { $set: data }, { new: true }).lean();
    return updated || null;
  } catch (error) {
    logger.error("Error in updateJob service:", error);
    throw error;
  }
}

export async function deleteJob(id) {
  try {
    if (!id) {
      throw new Error("Job ID is required");
    }
    const res = await JobModel.findByIdAndDelete(id).lean();
    return !!res;
  } catch (error) {
    logger.error("Error in deleteJob service:", error);
    throw error;
  }
}




