const express = require('express');
const mysql = require('mysql2/promise');
const router = express.Router();
const crypto = require('crypto-js');
require('dotenv').config();

// Create connection pool to MySQL database
const pool = mysql.createPool({
  host: process.env.DATABASE_HOST || 'localhost',
  user: process.env.DATABASE_USER || 'root',
  password: process.env.DATABASE_PASSWORD || '',
  database: process.env.DATABASE_NAME || 'deployer',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

// Generate a secure token
const generateToken = (length = 64) => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let token = '';
  for (let i = 0; i < length; i++) {
    token += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return token;
};

/**
 * Login endpoint to authenticate users against the database
 */
router.post('/', async (req, res) => {
  const { email, password } = req.body;

  // Basic validation
  if (!email || !password) {
    return res.status(400).json({
      success: false,
      error: 'Email and password are required'
    });
  }

  try {
    // Query database for user with matching email
    const [rows] = await pool.query(
      'SELECT * FROM User WHERE email = ?',
      [email]
    );

    // Check if user exists
    if (rows.length === 0) {
      return res.status(401).json({
        success: false,
        error: 'User not found'
      });
    }

    const user = rows[0];

    // Check if user is active
    if (!user.active) {
      return res.status(401).json({
        success: false,
        error: 'Account is inactive'
      });
    }

    // Verify password (compare hashed passwords)
    if (user.password !== password) {
      return res.status(401).json({
        success: false,
        error: 'Invalid credentials'
      });
    }

    // Generate token
    const token = generateToken();

    // Update last login timestamp
    await pool.query(
      'UPDATE User SET lastLogin = NOW() WHERE id = ?',
      [user.id]
    );

    // Return success with token and user info
    return res.json({
      success: true,
      token,
      user: {
        id: user.id,
        name: `${user.name} ${user.surname}`,
        email: user.email,
        role: user.role
      }
    });
  }
  catch (error) {
    console.error('Authentication error:', error);
    return res.status(500).json({
      success: false,
      error: 'Internal server error'
    });
  }
});

module.exports = router;