require('dotenv').config()
const express = require('express');
const session = require('express-session')
const { Sequelize, DataTypes } = require('sequelize');
const SequelizeStore = require('connect-session-sequelize')(session.Store)
const path = require('path')
const app = express();
const port = 3000;

const sequelize = new Sequelize({
    dialect: 'postgres',
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    database: process.env.DB_DATABASE,
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
})

const PlayerModel = sequelize.define('player', {
    id: {type: DataTypes.INTEGER, primaryKey: true, unique: true, autoIncrement: true},
    username: {type: DataTypes.STRING},
    password: {type: DataTypes.STRING},
    level: {type: DataTypes.INTEGER, defaultValue: 0},
})

const sessionStore = new SequelizeStore({
    db: sequelize,
    tableName: 'connections',
})

app.use(express.static(path.join(__dirname, 'files')))

app.use(express.urlencoded({ extended: true }));

app.use(session({
    secret: process.env.SESSION_JWT,
    store: sessionStore,
    resave: false,
    saveUninitialized: true,
    cookie: { secure:false }
}));

const start = async() => {
    try {
        await sequelize.authenticate();
        console.log('Успешное подключение БД')

        await sequelize.sync({ alter:true })
        console.log('Синхронизация моделей завершена.')

        sessionStore.sync();
        console.log('Синхронизация сессий завершена.')
       
    } catch (error) {
        console.log(`Ошибка подключения к БД: ${error}`)
    }
}

start()

// Middleware для обработки данных из формы


const requireLogin = (req, res, next) => {
    if (req.session.user) {
        next();
    } else {
        res.redirect('/login')
    }
};

app.get('/', async (req, res) => {
    res.sendFile(path.join(__dirname, '/files/html/index.html'))
});

// Главная страница с формой логина
app.get('/login', (req, res) => {
    res.sendFile(path.join(__dirname, '/files/html/login.html'))
});

// Обработка логина
app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await PlayerModel.findOne({where: { username: username, password: password}})

  if (user) {
    req.session.user = user;
    res.redirect('/')
  } else {
    res.send('<h1>Неверное имя пользователя или пароль</h1><a href="/">Попробовать снова</a>');
  }
});

app.get('/register', (req, res) => {
    res.sendFile(path.join(__dirname, '/files/html/register.html'))
})

app.post('/register', async (req, res) =>{
    const {username, password, password_repeat} = req.body

    if (password !== password_repeat) {
        res.send(`<script>alert('Пароли не совпадают'); window.location.href='/register'</script>`)
    }
    await PlayerModel.create({
        username: username,
        password: password,
    })
    
    console.log(users)
})

app.get('/logout', (req, res) => {
    req.session.destroy(err => {
        if (err) {
            return res.send('Ошибка при выходе');
        }
        res.redirect('/login')
    })
})

// Запуск сервера
app.listen(port, () => {
  console.log(`Сервер запущен на http://localhost:${port}`);
});