import { generateToken, verifyToken } from '../auth/auth.js';
import { connection } from '../configs/db.js';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import express from "express";
import dotenv from 'dotenv';

dotenv.config();
const secret = process.env.JWT_SECRET;

const authRoute = express.Router();

// Register
authRoute.post('/register', async (req, res) => {
    try {
        const { email, password } = req.body;
        if (!email || !password) return res.status(400).json({ message: 'Please provide all required fields' });

        const [existing] = await connection.query('SELECT * FROM users WHERE email = ?', [email]);
        if (existing.length > 0) return res.status(400).json({ message: 'Email already exists' });

        const hashedPassword = await bcrypt.hash(password, 10);
        const [result] = await connection.query('INSERT INTO users (email, password) VALUES (?, ?)', [email, hashedPassword]);

        const user = { user_id: result.insertId, email };
        const token = jwt.sign({ user_id: user.user_id, email: user.email }, secret, { expiresIn: '30d' });

        return res.status(201).json({ message: 'User registered successfully', token, user });
    } catch (err) {
        console.log(err);
        return res.status(500).json({ message: "Internal server error" });
    }
});

// Login
authRoute.post('/login', async (req, res) => {
    try {
        const { email, password } = req.body;
        if (!email || !password) return res.status(400).json({ message: 'Please provide all required fields' });

        const [users] = await connection.query('SELECT * FROM users WHERE email = ?', [email]);
        if (users.length === 0) return res.status(400).json({ message: 'Invalid email or password' });

        const user = users[0];
        const isPasswordCorrect = await bcrypt.compare(password, user.password);
        if (!isPasswordCorrect) return res.status(400).json({ message: 'Invalid email or password' });

       await generateToken(user, res)

        return res.status(200).json({ message: 'Login successful', user: { user_id: user.user_id, email: user.email } });
    } catch (err) {
        console.log(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

// Logout
authRoute.get('/logout', (req, res) => {
    res.clearCookie('token');
    return res.status(200).json({ message: 'Logged out successfully' });
});

// Check auth
authRoute.get("/check", verifyToken, (req, res) => {
    try {
        const user_id = req.user.user_id;
        const email = req.user.email;
        return res.status(200).json({ user_id, email });
    } catch (err) {
        console.log(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

export default authRoute;