const express = require("express");
const bcrypt = require("bcrypt");
const { query } = require("../config/database");
const router = express.Router();

// Login endpoint (JSON API)
router.post("/login", async (req, res) => {
  const { email, password } = req.body;
  try {
    const result = await query(
      `
      SELECT u.id, u.email, u.username, u.passwordhash, u.role_id, u.isactive,
             r.name as role_name, r.permissions
      FROM adminusers u
      LEFT JOIN roles r ON u.role_id = r.id
      WHERE u.email = $1
    `,
      [email]
    );

    if (result.rows.length === 0) {
      return res
        .status(401)
        .json({ success: false, message: "Invalid email or password" });
    }

    const admin = result.rows[0];

    // Check if user is active
    if (!admin.isactive) {
      return res
        .status(401)
        .json({ success: false, message: "Account is deactivated" });
    }

    const validPassword = await bcrypt.compare(password, admin.passwordhash);
    if (!validPassword) {
      return res
        .status(401)
        .json({ success: false, message: "Invalid email or password" });
    }

    // Update last login
    await query("UPDATE adminusers SET last_login = NOW() WHERE id = $1", [
      admin.id,
    ]);

    // Store user info in session
    req.session.user = {
      id: admin.id,
      email: admin.email,
      username: admin.username,
      role_id: admin.role_id,
      role_name: admin.role_name,
      permissions: admin.permissions,
    };

    // Save session before responding
    req.session.save((err) => {
      if (err) {
        console.error("Session save error:", err);
        return res
          .status(500)
          .json({ success: false, message: "Session error" });
      }

      res.json({
        success: true,
        user: req.session.user,
      });
    });
  } catch (error) {
    console.error("Login error:", error);
    res.status(500).json({ success: false, message: "Server error" });
  }
});

// Check session endpoint
router.get("/session", (req, res) => {
  if (req.session && req.session.user) {
    res.json({
      authenticated: true,
      user: req.session.user,
    });
  } else {
    res.status(401).json({ authenticated: false });
  }
});

// Logout endpoint
router.post("/logout", (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      console.error("Logout error:", err);
      return res.status(500).json({ success: false, message: "Logout failed" });
    }
    res.json({ success: true, message: "Logged out successfully" });
  });
});

module.exports = router;
