const express = require('express');
const bcrypt = require('bcrypt');
const mysql = require('mysql2/promise');
const config = require("./config/db.config.js");
const router = express.Router();
const multer = require('multer');


const storage = multer.memoryStorage(); // Store files in memory
const upload = multer({
  storage: storage,
  limits: { fileSize: 64 * 1024 } // Limit to 64 KB
});

// Create a connection pool
const pool = mysql.createPool({
    host: config.host,
    user: config.user,
    password: config.password,
    database: config.database,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
  });
  
// Default avatar buffer (base64 encoded or binary data)
const defaultAvatarBuffer = Buffer.from('UklGRlYDAABXRUJQVlA4IEoDAACwEgCdASpkAGQAPm0ylkekIqIhJpM7EIANiWkAFs6tQPy9d+/kCpiZj46PqX2Cf1s6vv7gFlcGy8GuVKz1sdC/dH5IfQePmbNKRqlkS5KofryVMES8OWaaCn4wjzYV6JN24CKoaNLEbpYeWkln493+j+aL2yMpUOl2PTUT853EL93KnDzFbjkRzZm4yepG1Xv6aXyFAdLiBGsXU3VEEAD++pWZOAJeXUf0nSxwdQhs5sUQMamUGMgYF/T+mPuqp2n7SZtXQAI3y982oC9FVCL1Wxkd8iQxf+kdTcTtXSihJtYMjv6O83cJ7I63fzSgCu1Cg0V+bPUd5p/lIM3s2yG+zlAm41qgUHXY6APIwoYnZHbmaPo/Ae0A5TMLMTzI811tC8KzIJaFgZAaIkGSlwdJJ6OB44nWkFUvvS5DI7WbsnmN+ODQJ/ZnOxFQAF8thZOM+R/zPGfkykrDeCmKl675UpJ4T6cHT65+T533XZLQYkxPwNtMfzJfcHsXoWTg4XtYh9QEkyT5CUc0w7Pkid0MyUV1eY0DV51HJujYWniM4owiJsuC/Bs/Ms6QoWlVsQSZ33iUhE0dem0ZEbT2SoqmGbp5e++GgIxGEm6120qoA802YzXm1LbYgOe3+/dvxQNAvJcKeZNGbVo/V/rSAT9ZX1ISi5kz1w32oJevgKOpJcqC44czmaJKrMBQFtcK2iuFp8KvhFXaUcFSr0sOQKZOvbhNeoGJfWq92vgNvBk0hJHu7HpSxKlCsNlGiwpwvlmWBvQGMi897HIU4ozprBqoc/1kI8yMHJTNVG9un+czA/3bHkP7v5tlyXx2cbfODTimFNc+C4sA3QdDX2a7a0MBuNsX7im51ny2ABSKJgBJEiJHxVcse1pzO+WwfYwU0orZWbYXAwb3DAd4c/Oaj/5H/fqwsb0GBu9ocDe5gXvL6ngJ7Aej/5SNIK44nR1Ik2hsGOldyihgIws16zmANwLGUECB46Bni0gaGgF6SaeoWv5XykxS3VNte/2mnR4P/YZ3J9VkAEeDLRnOnSFss2F0lSaLY8EFIiPgB0TnrWWMjOfx+XKZ0+X7Ef2XI9cdFMpLhWUAjY458nnh/feojuqi3h8dX35dECUwAA==', 'base64'); // Replace with actual base64 string of your default avatar

// Updated signup route to handle file uploads
router.post('/signup', upload.single('avatar'), async (req, res) => {

     // Check if signup is enabled
     if (!config.enableSignup) {
        return res.status(403).send(`
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Signup Disabled</title>
                <style>
                    body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
                    h1 { color: red; }
                    button { padding: 10px 20px; font-size: 16px; }
                </style>
            </head>
            <body>
                <h1>Signup is currently disabled.</h1>
                <p>Please contact the adminstrator for assistance.</p>
                <button onclick="window.location.href='/'">Back to < POS Diagnostic Assist > </button>
            </body>
            </html>
        `);
    }

    const { username, email, password } = req.body;
    const avatar = req.file ? req.file.buffer : defaultAvatarBuffer; // Use default avatar if no file uploaded
  
    // Validate username and password lengths
    if (!username || username.length <= 4) {
        return res.redirect('signup?message=Username must be more than 4 characters.');
    }
    
    if (!password || password.length <= 8) {
        return res.redirect('signup?message=Password must be more than 8 characters.');
    }

    // Check if all required fields are provided
    if (!email) {
        return res.redirect('signup?message=Please provide an email.');
    }
  
    try {
        // Get a connection from the pool
        const connection = await pool.getConnection();
        
        // Check for existing username or email
        const [rows] = await connection.execute(
            'SELECT * FROM accounts WHERE username = ? OR email = ?',
            [username, email]
        );

        if (rows.length > 0) {
            connection.release();
            return res.redirect('signup?message=Username or email already exists.');
        }

        // Hash the password
        const hashedPassword = await bcrypt.hash(password, 10);
  
        // Insert new user into the database
        await connection.execute(
            'INSERT INTO accounts (username, email, password, avatar) VALUES (?, ?, ?, ?)',
            [username, email, hashedPassword, avatar] // Include avatar buffer here
        );
  
        // Release the connection back to the pool
        connection.release();
  
        // Respond with success message
        res.redirect('signup?message=User registered successfully!');
    } catch (error) {
        console.error('Database error:', error);
        
        // Handle other errors
        res.redirect('signup?message=An unexpected error occurred.');
    }
});

module.exports = router;
