require('dotenv').config();
const loggingService = require('./services/loggingService');
const db = require('./db_config');

async function testLogging() {
    console.log("Testing MariaDB Logging...");

    const testSource = '628123456789@c.us';
    const testTarget = '628987654321@c.us';
    const testMessage = 'Test Message ' + Date.now();

    try {
        // 1. Log a message
        console.log("1. Logging message...");
        await loggingService.logMessage(testSource, testTarget, testMessage, 'INCOMING');
        console.log("   Logged.");

        // 2. Retrieve messages
        console.log("2. Retrieving messages...");
        const messages = await loggingService.getMessages(testSource);

        const found = messages.find(m => m.message_content === testMessage);

        if (found) {
            console.log("   SUCCESS: Message found in DB.");
            console.log("   Source:", found.source_number);
            console.log("   Target:", found.target_number);
        } else {
            console.error("   FAILURE: Message not found.");
            process.exit(1);
        }

        // 3. Test Contacts
        console.log("3. Testing Contact Save...");
        await loggingService.saveContact(testSource, 'Test User', 'Bestie', 1);

        // Manual verification query
        const [contacts] = await db.execute("SELECT * FROM contacts WHERE phone = ?", [testSource]);
        if (contacts.length > 0 && contacts[0].name === 'Test User') {
            console.log("   SUCCESS: Contact saved.");
        } else {
            console.error("   FAILURE: Contact not saved.");
        }

        console.log("Verification Complete.");
        process.exit(0);

    } catch (e) {
        console.error("Test Failed:", e);
        process.exit(1);
    }
}

testLogging();
