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();
    
    // Handle null jobId in populate results
    return items.map(item => ({
      ...item,
      jobId: item.jobId || null
    }));
  } 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();
    if (!item) return null;
    return {
      ...item,
      jobId: item.jobId || null
    };
  } catch (error) {
    logger.error("Error in getApplicationById service:", error);
    throw error;
  }
}

export async function createApplication(data) {
  try {
    logger.info("Creating application in database with data:", data);
    
    // Only populate if jobId exists
    const created = await ApplicationModel.create(data);
    logger.info(`Application created in database with ID: ${created._id}`);
    
    let populated;
    if (created.jobId) {
      populated = await ApplicationModel.findById(created._id)
        .populate("jobId", "title department location employmentType")
        .lean();
    } else {
      populated = await ApplicationModel.findById(created._id).lean();
    }
    
    return {
      ...populated,
      jobId: populated?.jobId || null
    };
  } catch (error) {
    logger.error("Error in createApplication service:", error);
    logger.error("Error details:", {
      message: error.message,
      stack: error.stack,
      name: error.name,
      code: error.code
    });
    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();
    if (!updated) return null;
    return {
      ...updated,
      jobId: updated.jobId || 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;
  }
}

