import { ApplicationModel } from "../models/application.model.js";
import logger from "../utils/logger.js";

export async function listApplications(filters = {}) {
  try {
    const query = {};
    
    if (filters.status && filters.status !== "All") {
      query.status = filters.status;
    }
    
    if (filters.jobId) {
      query.jobId = filters.jobId;
    }

    const items = await ApplicationModel.find(query)
      .populate("jobId", "title department location employmentType")
      .sort({ createdAt: -1 })
      .lean();
    return items;
  } catch (error) {
    logger.error("Error in listApplications service:", error);
    throw error;
  }
}

export async function getApplicationById(id) {
  try {
    if (!id) {
      throw new Error("Application ID is required");
    }
    const item = await ApplicationModel.findById(id)
      .populate("jobId", "title department location employmentType description")
      .lean();
    return item || null;
  } catch (error) {
    logger.error("Error in getApplicationById service:", error);
    throw error;
  }
}

export async function createApplication(data) {
  try {
    const created = await ApplicationModel.create(data);
    const populated = await ApplicationModel.findById(created._id)
      .populate("jobId", "title department location employmentType")
      .lean();
    return populated;
  } catch (error) {
    logger.error("Error in createApplication service:", error);
    throw error;
  }
}

export async function updateApplication(id, data) {
  try {
    if (!id) {
      throw new Error("Application ID is required");
    }
    const updated = await ApplicationModel.findByIdAndUpdate(
      id,
      { $set: data },
      { new: true, runValidators: true }
    )
      .populate("jobId", "title department location employmentType")
      .lean();
    return updated || null;
  } catch (error) {
    logger.error("Error in updateApplication service:", error);
    throw error;
  }
}

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

