require('dotenv').config();

const sequelize = require('./db'); // Подключение базы данных

// Настраиваем глобальные переменные (опционально)
global.path = require('path');
global.config = require('./config'); // Конфигурация
global.database = sequelize; // База данных
global.utils = require('./utils');
const express = require('express');
const { UserModel, CharacterModel, BusinessModel, EnterpriseModel, WarehouseModel } = global.config;
const app = express();

app.use(express.static('public')); // Для выдачи HTML и статики

// Эндпоинт для получения всех данных игрока
app.get('/player/:id', async (req, res) => {
    const playerId = req.params.id;

    try {
        const user = await UserModel.findOne({ where: { telegram_id: req.params.id } });
        const character = await CharacterModel.findOne({ where: { telegram_id: playerId } });
        let business = await BusinessModel.findOne({ where: { owner: playerId } })
        if(business === null){
            business = await BusinessModel.findOne( {where: { owner: user.business.id} } )
        }
        const enterprises = await EnterpriseModel.findAll({ where: { playerId } });
        const warehouse = await WarehouseModel.findOne({ where: { playerId } });

        if (!user || !character) {
            return res.status(404).json({ error: "Игрок не найден." });
        }

        res.json({
            user: {
                username: user.username,
                telegramID: user.telegram_id,
                name: user.name,
                status: user.status,
                profileLevel: user.level,
                characterLevel: character.level,
                profileExp: user.exp,
                characterExp: character.exp,
                profileExpToUp: global.config.expToUp[user.level],
                characterExpToUp: global.config.expToUp[character.level],
                hp: character.hp,
                maxHp: character.max_hp,
                stamina: character.stamina,
                maxStamina: character.max_stamina,
                force: character.force,
                intelligence: character.intelligence,
                resilience: character.resilience,
                endurance: character.endurance,
                money: global.utils.spaces(user.money),
                dirtymoney: global.utils.spaces(character.dirtymoney),
            },
            business: business || { name: "Отсутствует", balance: 0, materials: 0, users: [] },
            enterprises: enterprises || [],
            warehouse: warehouse || { materials: 0, maxMaterials: 0 },
        });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Ошибка сервера' });
    }
});

app.get('/scoreboard', (req, res) => {
    res.sendFile(global.path.join(__dirname, 'public', 'scoreboard.html'));
});

app.get('/users', async (req, res) => {
    const { sortBy } = req.query; // Sorting option passed as a query parameter
    
    const sortOptions = {
        money: [sequelize.literal('money'), 'DESC'],
        level: [sequelize.literal('level'), 'DESC']
    };
    
    const topUser = await UserModel.findAll({
        attributes: ['username', 'money', 'level', 'status'],
        order: [sortOptions[sortBy] || sortOptions['money']], // Default sort by money
        limit: 15
    });

    res.json(topUser.map(player => ({
        username: player.username,
        money: utils.spaces(player.money),
        level: player.level,
        status: player.status
    })));
});


app.get('/characters', async (req, res) => {
    const { sortBy } = req.query; // Use query parameters to specify sorting
    
    const sortOptions = {
        dirtymoney: [sequelize.literal('dirtymoney'), 'DESC'],
        level: [sequelize.literal('level'), 'DESC'],
        force: [sequelize.literal('force'), 'DESC'],
        intelligence: [sequelize.literal('intelligence'), 'DESC'],
        resilience: [sequelize.literal('resilience'), 'DESC'],
        endurance: [sequelize.literal('endurance'), 'DESC']
    };
    
    const topCharacter = await CharacterModel.findAll({
        attributes: ['username', 'dirtymoney', 'level', 'force', 'intelligence', 'resilience', 'endurance'],
        order: [sortOptions[sortBy] || sortOptions['dirtymoney']], // Default sort by dirtymoney
        limit: 15
    });

    res.json(topCharacter.map(character => ({
        username: character.username,
        dirtymoney: utils.spaces(character.dirtymoney),
        level: character.level,
        force: character.force,
        intelligence: character.intelligence,
        resilience: character.resilience,
        endurance: character.endurance
    })));
});


app.get('/enterprises', async (req, res) => {
    const enterprises = await EnterpriseModel.findAll({
        attributes: ['name', 'resourceType', 'level', 'efficiency', 'warehouseCapacity', 'currentResources', 'playerId']
    });

    const resourceIcons = {
        wood: '🌳',
        coal: '⛏️',
        oil: '🛢️',
        metall: '⚒️',
        gold: '💰',
        diamond: '💎'
    };

    const enterprisesData = await Promise.all(enterprises.map(async enterprise => {
        const player = await UserModel.findOne({
            attributes: ['name'],
            where: { telegram_id: enterprise.playerId }
        });

        return {
            name: enterprise.name,
            resourceType: enterprise.resourceType,
            level: enterprise.level,
            efficiency: enterprise.efficiency,
            warehouseCapacity: enterprise.warehouseCapacity,
            currentResources: enterprise.currentResources,
            owner: player ? player.name : 'Unknown',
            icon: resourceIcons[enterprise.resourceType] || '❓'
        };
    }));

    res.json(enterprisesData);
});

app.get('/businesses', async (req, res) => {
    const { sortBy } = req.query; // Sorting option passed as a query parameter
    
    const sortOptions = {
        balance: [sequelize.literal('balance'), 'DESC'],
        usersCount: [sequelize.literal('ARRAY_LENGTH(users, 1)'), 'DESC']
    };

    const businesses = await BusinessModel.findAll({
        attributes: ['name', 'balance', 'users', 'owner'],
        order: [sortOptions[sortBy] || sortOptions['balance']], // Default sort by balance
        limit: 15
    });

    const businessesData = await Promise.all(businesses.map(async business => {
        const owner = await UserModel.findOne({
            attributes: ['username'],
            where: { telegram_id: business.owner }
        });

        return {
            name: business.name,
            balance: utils.spaces(business.balance),
            usersCount: business.users.length,
            owner: owner ? owner.username : 'Unknown'
        };
    }));

    res.json(businessesData);
});


// Запуск сервера
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`Сервер запущен на порту ${PORT}`));
