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

const testExpense = {
    expense_date: new Date().toISOString().split('T')[0],
    category: 'Other',
    description: 'Test Expense for Deletion',
    amount: 500
};

console.log('Starting Expense Deletion Test...');

db.serialize(() => {
    // 1. Insert Expense
    db.run('INSERT INTO expenses (expense_date, category, description, amount) VALUES (?, ?, ?, ?)',
        [testExpense.expense_date, testExpense.category, testExpense.description, testExpense.amount],
        function (err) {
            if (err) {
                console.error('Error inserting expense:', err);
                process.exit(1);
            }

            const expenseId = this.lastID;
            console.log(`Expense inserted with ID: ${expenseId}`);

            // 2. Verify Insertion
            db.get('SELECT * FROM expenses WHERE id = ?', [expenseId], (err, row) => {
                if (err || !row) {
                    console.error('Error verifying insertion:', err || 'Row not found');
                    process.exit(1);
                }
                console.log('Expense verification successful (it exists).');

                // 3. Delete Expense
                db.run('DELETE FROM expenses WHERE id = ?', [expenseId], function (err) {
                    if (err) {
                        console.error('Error deleting expense:', err);
                        process.exit(1);
                    }

                    if (this.changes === 0) {
                        console.error('Deletion failed: No rows affected.');
                        process.exit(1);
                    }

                    console.log('Expense deletion command executed.');

                    // 4. Verify Deletion
                    db.get('SELECT * FROM expenses WHERE id = ?', [expenseId], (err, row) => {
                        if (err) {
                            console.error('Error verifying deletion:', err);
                            process.exit(1);
                        }

                        if (!row) {
                            console.log('Test Passed: Expense successfully deleted.');
                            process.exit(0);
                        } else {
                            console.error('Test Failed: Expense still exists after deletion.');
                            process.exit(1);
                        }
                    });
                });
            });
        }
    );
});
