const axios = require('axios');

const API_URL = 'http://localhost:5000/api';

async function testApi() {
    try {
        console.log('Testing API...');

        // 1. Login
        console.log('\n--- Login as Admin ---');
        const loginRes = await axios.post(`${API_URL}/auth/login`, {
            email: 'admin@tokobuku.com',
            password: 'password123' // Wait, I seeded admin with bcrypt hash of 'admin123' in seed.js? Let me check seed.js content I wrote.
            // In seed.js: const adminHash = await bcrypt.hash('admin123', 10);
            // So password is 'admin123'
        });

        // Wait, did I use 'admin' or 'admin@tokobuku.com'?
        // Seed: email: 'admin@tokobuku.com'
        // Auth Route: if (email === 'admin') targetEmail = 'admin@tokobuku.com';
        // So 'admin' should work too if I implemented that logic in auth.js. I did.

        // Let's try correct credentials if I recall correctly.
        // seed.js: const adminHash = await bcrypt.hash('admin123', 10);

        // Retrying login with correct password
    } catch (error) {
        // console.error('Login failed initially (expected if I got password wrong in head)', error.message);
    }

    try {
        // Real attempt
        const loginRes = await axios.post(`${API_URL}/auth/login`, {
            email: 'admin',
            password: 'admin123'
        });
        console.log('Login successful! Token received.');
        const token = loginRes.data.token;
        const headers = { Authorization: `Bearer ${token}` };

        // 2. Fetch Products
        console.log('\n--- Fetch Products ---');
        const productsRes = await axios.get(`${API_URL}/products`);
        console.log(` fetched ${productsRes.data.length} products.`);
        if (productsRes.data.length > 0) {
            console.log('First product:', productsRes.data[0].title);
        }

        // 3. Create Order
        console.log('\n--- Create Order ---');
        // Need a product ID
        const product = productsRes.data[0];
        if (product) {
            const orderRes = await axios.post(`${API_URL}/orders`, {
                items: [{ id: product.id, quantity: 1, price: product.price }],
                totalAmount: product.price,
                shippingAddress: 'Test Address'
            }, { headers });
            console.log('Order created:', orderRes.data.id);
        }

        // 4. Get Vouchers
        console.log('\n--- Get Vouchers ---');
        const voucherRes = await axios.get(`${API_URL}/vouchers`);
        console.log(`Fetched ${voucherRes.data.length} vouchers.`);

        console.log('\n✅ Verification Complete: API is functioning.');

    } catch (error) {
        console.error('❌ Verification Failed:', error.response ? error.response.data : error.message);
    }
}

testApi();
