import mongoose from 'mongoose';
import { Project } from '../models/Project';

/**
 * Find project by ID or code, handling both ObjectId and string IDs
 * This function avoids Mongoose casting errors for string IDs
 */
export async function findProjectByIdOrCode(identifier: string): Promise<{ _id: any } | null> {
  // If it's a valid ObjectId, use Mongoose directly
  if (mongoose.Types.ObjectId.isValid(identifier)) {
    const project = await Project.findById(identifier).select('_id').lean();
    return project;
  }

  // For string IDs, use native MongoDB to avoid casting errors
  const db = mongoose.connection.db;
  if (!db) return null;
  const projectsCollection = db.collection('projects');

  // Try by _id first (string ID)
  let project = await projectsCollection.findOne(
    { _id: identifier } as any,
    { projection: { _id: 1 } }
  );
  
  // If not found, try by code
  if (!project) {
    project = await projectsCollection.findOne(
      { code: identifier },
      { projection: { _id: 1 } }
    );
  }
  
  return project;
}
