
import mongoose from 'mongoose';
import { Contract } from '../models/Contract';
import { Project } from '../models/Project';
import dotenv from 'dotenv';
import path from 'path';

// Load env vars
dotenv.config({ path: path.join(__dirname, '../../.env') });

const connectDB = async () => {
    try {
        await mongoose.connect(process.env.MONGODB_URI as string);
        console.log('MongoDB Connected');
    } catch (err) {
        console.error('MongoDB Connection Error:', err);
        process.exit(1);
    }
};

const runDebug = async () => {
    await connectDB();

    const targetProjectId = "s1768031889939";
    console.log(`Checking for project: ${targetProjectId}`);

    if (!mongoose.connection.db) {
        console.error("Database connection not ready");
        process.exit(1);
    }

    // Check Project existence directly with native driver
    const projectsCollection = mongoose.connection.db.collection('projects');
    const projectNative = await projectsCollection.findOne({ _id: targetProjectId } as any);
    console.log('Project (Native findOne):', projectNative);

    // Check Project with Mongoose
    const projectMongoose = await Project.findOne({ _id: targetProjectId });
    console.log('Project (Mongoose findById):', projectMongoose);

    // Check Contracts
    console.log(`Checking contracts for projectId: ${targetProjectId}`);

    // Native
    const contractsCollection = mongoose.connection.db.collection('contracts');
    const contractsNative = await contractsCollection.find({ projectId: targetProjectId } as any).toArray();
    console.log(`Contracts (Native): found ${contractsNative.length}`);
    contractsNative.forEach(c => console.log(` - Contract: ${c.contractNumber}, projectId: ${c.projectId} (type: ${typeof c.projectId})`));

    // Mongoose
    const contractsMongoose = await Contract.find({ projectId: targetProjectId });
    console.log(`Contracts (Mongoose simple): found ${contractsMongoose.length}`);

    // Mongoose OR
    const queryConditions: any[] = [{ projectId: targetProjectId }];
    const contractsMongooseOr = await Contract.find({ $or: queryConditions });
    console.log(`Contracts (Mongoose OR): found ${contractsMongooseOr.length}`);

    // Log all contracts just in case
    if (contractsNative.length === 0) {
        console.log("No contracts found for exact ID match. Listing ALL contracts to spy:");
        const allContracts = await contractsCollection.find({}).toArray();
        allContracts.forEach((c: any) => console.log(` - Contract ID: ${c._id}, Number: ${c.contractNumber}, projectId: ${c.projectId} (type: ${typeof c.projectId})`));
    }

    process.exit(0);
};

runDebug();
