const sqlite3 = require('sqlite3').verbose();
const path = require('path');

const db = new sqlite3.Database(path.join(__dirname, 'inventory.db'));

const transaction = {
    transaction_date: new Date().toISOString().split('T')[0],
    payment_type: 'Cash',
    customer_name: 'Test Customer',
    total_amount: 100,
    discount_percentage: 0,
    discount_amount: 0,
    amount_paid: 100
};

// We need a valid SKU ID first
db.get('SELECT id, current_stock FROM skus LIMIT 1', (err, sku) => {
    if (err) {
        console.error('Error fetching SKU:', err);
        process.exit(1);
    }

    if (!sku) {
        console.log('No SKUs found to test with. Inserting a dummy transaction without items (if allowed) or aborting.');
        console.log('Aborting test as we need items for real transaction flow in server.js');
        process.exit(0);
    }

    const items = [
        {
            sku_id: sku.id,
            quantity: 1,
            unit_price: 100
        }
    ];

    console.log('Testing transaction with SKU:', sku.id);

    // Simulate the server.js transaction logic manually or use axios to hit the running server?
    // Since we don't know if the server is running, let's try to hit the API if possible, 
    // BUT `server.js` might not be running in this environment context easily reachable via localhost if I don't start it.
    // I'll just run the SQL directly to see if it prepares correctly, mimicking server.js

    db.serialize(() => {
        db.run('BEGIN TRANSACTION');

        const transQuery = `
            INSERT INTO transactions (transaction_date, payment_type, customer_name, total_amount, discount_percentage, discount_amount, amount_paid)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        `;

        db.run(transQuery, [
            transaction.transaction_date,
            transaction.payment_type,
            transaction.customer_name,
            transaction.total_amount,
            transaction.discount_percentage,
            transaction.discount_amount,
            transaction.amount_paid
        ], function (err) {
            if (err) {
                console.error('Transaction INSERT failed:', err);
                db.run('ROLLBACK');
                process.exit(1);
            } else {
                console.log('Transaction INSERT success. ID:', this.lastID);
                // We won't insert items or update stock to avoid messing up data too much, 
                // just checking if the INSERT into transactions table works with the new column.
                db.run('ROLLBACK'); // Rollback so we don't keep test data
                console.log('Rolled back test transaction.');
                process.exit(0);
            }
        });
    });
});
