import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { env } from "../config/env.js";
import { getDb } from "../config/db.js";
import { logAction } from "../utils/audit.helper.js";

export const login = async (req, res) => {
  const { email, password } = req.body;
  const db = getDb();
  const [rows] = await db.execute(
    `SELECT u.id, u.name, u.email, u.password_hash, u.role, u.notary_id, u.password_must_change,
            n.name AS notary_name, n.region, n.district, n.category, n.status AS notary_status,
            n.issued_date, n.expired_date
     FROM users u
     LEFT JOIN notaries n ON n.id = u.notary_id
     WHERE u.email = ? AND u.is_active = 1
     LIMIT 1`,
    [email]
  );
  const user = rows[0];

  if (!user) {
    return res.status(401).json({ message: "Invalid credentials" });
  }

  const matched = await bcrypt.compare(password, user.password_hash);

  if (!matched) {
    return res.status(401).json({ message: "Invalid credentials" });
  }

  const token = jwt.sign({ userId: user.id, role: user.role }, env.jwtSecret, {
    expiresIn: "8h"
  });

  await logAction(user.id, "LOGIN", `User logged in from ${req.ip || 'unknown'}`);

  return res.json({
    token,
    user: {
      id: user.id,
      name: user.name,
      email: user.email,
      role: user.role,
      password_must_change: user.password_must_change,
      notary: user.notary_id
        ? {
            id: user.notary_id,
            name: user.notary_name,
            region: user.region,
            district: user.district,
            category: user.category,
            status: user.notary_status,
            issued_date: user.issued_date,
            expired_date: user.expired_date
          }
        : null
    }
  });
};

export const changePassword = async (req, res) => {
  const { new_password } = req.body;
  const db = getDb();
  const passwordHash = await bcrypt.hash(new_password, 10);

  await db.execute(
    `UPDATE users SET password_hash = ?, password_must_change = 0 WHERE id = ?`,
    [passwordHash, req.user.id]
  );

  await logAction(req.user.id, "CHANGE_PASSWORD", `User changed their own password`);

  res.json({ message: "Password updated successfully" });
};
