import { UserResumeModel } from "../models/userResume.model.js";
import logger from "../utils/logger.js";

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

export async function listUserResumes(filters = {}) {
  try {
    const query = {};
    
    if (filters.email) {
      query.email = filters.email;
    }
    
    if (filters.jobId) {
      query.jobId = filters.jobId;
    }

    logger.info("listUserResumes - Query:", JSON.stringify(query));
    
    // Get database and collection info
    const db = UserResumeModel.db;
    const dbName = db?.databaseName || "unknown";
    logger.info(`listUserResumes - Database name: ${dbName}`);
    
    // Try to get collection name (might not be available until after first query)
    let collectionName = "unknown";
    try {
      collectionName = UserResumeModel.collection?.collectionName || "unknown";
      logger.info(`listUserResumes - Collection name: ${collectionName}`);
    } catch (e) {
      logger.warn("Could not get collection name before query:", e.message);
    }
    
    // First, try without populate to see if we get any results
    const countWithoutPopulate = await UserResumeModel.countDocuments(query);
    logger.info(`listUserResumes - Total documents matching query (without populate): ${countWithoutPopulate}`);
    
    // Now get collection name after query (should be available now)
    try {
      collectionName = UserResumeModel.collection?.collectionName || collectionName;
      logger.info(`listUserResumes - Collection name (after query): ${collectionName}`);
    } catch (e) {
      // Ignore
    }
    
    if (countWithoutPopulate === 0) {
      // Try to get total count in collection
      const totalInCollection = await UserResumeModel.countDocuments({});
      logger.info(`listUserResumes - Total documents in collection: ${totalInCollection}`);
      
      // List all collections in database for debugging
      if (db && totalInCollection === 0) {
        try {
          const collections = await db.listCollections().toArray();
          const collectionNames = collections.map(c => c.name);
          logger.warn(`listUserResumes - Available collections in database '${dbName}': ${collectionNames.join(", ")}`);
          logger.warn(`listUserResumes - Looking for collection: 'userresumes' or 'user_resumes'`);
        } catch (listError) {
          logger.error("Error listing collections:", listError.message);
        }
      }
    }

    const items = await UserResumeModel.find(query)
      .populate("jobId", "title department location")
      .sort({ createdAt: -1 })
      .lean();
    
    logger.info(`listUserResumes - Retrieved ${items.length} items after populate`);
    
    return items;
  } catch (error) {
    logger.error("Error in listUserResumes service:", error);
    logger.error("Error stack:", error.stack);
    throw error;
  }
}

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

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

