import express from "express";
import bcrypt from "bcryptjs";
import { query } from "../db.js";

const router = express.Router();

router.post("/", async (req, res) => {
  try {
    const username = String(req.body?.username || "").trim();
    const password = String(req.body?.password || "");

    if (!username || !password) {
      return res.status(422).json({ ok: false, error: "Username and password are required" });
    }

    const rows = await query(
      `SELECT id, username, display_name, password_hash, role, is_active
       FROM staff_users
       WHERE username = ?
       LIMIT 1`,
      [username]
    );

    const user = rows[0];
    if (!user || Number(user.is_active) !== 1) {
      return res.status(401).json({ ok: false, error: "Invalid credentials" });
    }

    const valid = bcrypt.compareSync(password, user.password_hash);
    if (!valid) {
      return res.status(401).json({ ok: false, error: "Invalid credentials" });
    }

    return res.json({
      ok: true,
      user: {
        id: String(user.id),
        username: user.username,
        displayName: user.display_name,
        role: user.role,
      }
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ ok: false, error: "Login failed" });
  }
});

export default router;
