const axios = require('axios');
const fs = require('fs');

const API_URL = 'http://localhost:5001/api';
let token = '';

async function loginAdmin() {
    try {
        const res = await axios.post(`${API_URL}/auth/login`, {
            email: 'admin@tokobuku.com',
            password: 'password123'
        });
        token = res.data.token;
        console.log('Admin logged in:', token ? 'Success' : 'Failed');
    } catch (err) {
        console.error('Login failed:', err.message);
        process.exit(1);
    }
}

async function checkBestSellers() {
    try {
        console.log('\n--- Checking Best Sellers Endpoint (Public) ---');
        // This is a public endpoint now
        const res = await axios.get(`${API_URL}/books/bestsellers`);
        console.log('Status:', res.status);
        console.log('Data Length:', res.data.length);
        if (res.data.length > 0) {
            console.log('Top 1 Book:', res.data[0].title, '| Sold:', res.data[0].sold);
        } else {
            console.log('No best sellers found (maybe no orders yet?)');
        }
    } catch (err) {
        console.error('Best Sellers check failed:', err.response ? err.response.data : err.message);
    }
}

async function checkAdminOrders() {
    try {
        console.log('\n--- Checking Admin Orders (For Dynamic Images) ---');
        const res = await axios.get(`${API_URL}/orders`, {
            headers: { Authorization: `Bearer ${token}` }
        });
        console.log('Status:', res.status);
        const orders = res.data;
        if (orders.length > 0) {
            const order = orders[0];
            console.log('First Order ID:', order.id);
            console.log('User Name:', order.User ? order.User.name : 'No User');
            console.log('User Image:', order.User ? order.User.image : 'No User');

            if (order.User && order.User.image) {
                console.log('SUCCESS: Order has User image linked dynamically.');
            } else {
                console.log('WARNING: User image is null/undefined. This might be normal if user has no image, but verify logic handles it.');
            }
        } else {
            console.log('No orders to check.');
        }
    } catch (err) {
        console.error('Admin Orders check failed:', err.response ? err.response.data : err.message);
    }
}

async function run() {
    await loginAdmin();
    // Create sales data if needed? 
    // Assuming seed data exists or previous tests created data.
    await checkBestSellers();
    await checkAdminOrders();
}

run();
