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: 'Ошибка сервера' });
    }
});


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