const db = require("../../managers/dbConfig");
const bcrypt = require("bcryptjs");
const validator = require("validator");

const updateProfile = async (req, res, next) => {
  try {
    const {
      staff_id,
      firstName,
      lastName,
      age,
      gender,
      email,
      address,
      phone_num,
      cadre,
      sPIN,
    } = req.body;

    //console.log(req.body);

    if (!staff_id) {
      return res.status(400).json({
        status: "failed",
        error: "Staff ID is required to update profile.",
      });
    }

    const checkStaffSql = `SELECT * FROM staffs WHERE staff_id = ?`;
    const [existingStaffRows] = await db.execute(checkStaffSql, [staff_id]);
    if (existingStaffRows.length === 0)
      throw `No staff found with ID ${staff_id}`;
    const existing = existingStaffRows[0];

    // 🔐 Validate and hash sPIN if provided
    let hashedPin = existing.sPIN;
    //console.log(hashedPin);
    if (sPIN) {
      console.log(sPIN);
      if (!validator.isNumeric(sPIN.toString()) || sPIN.length < 4) {
        console.log(sPIN.length);
        return res.status(400).json({
          status: "failed",
          error:
            "sPIN must be at least 4 digits long and contain only numbers.",
        });
      }
      // console.log("got here");
      const salt = await bcrypt.genSalt();
      hashedPin = await bcrypt.hash(sPIN, salt);
    }

    const updateSql = `
      UPDATE staffs SET 
        firstName = ?, 
        lastName = ?, 
        age = ?, 
        gender = ?, 
        email = ?, 
        address = ?, 
        phone_num = ?, 
        cadre = ?, 
        sPIN = ?
      WHERE staff_id = ?`;

    await db.execute(updateSql, [
      firstName || existing.firstName,
      lastName || existing.lastName,
      age || existing.age,
      gender || existing.gender,
      email || existing.email,
      address || existing.address,
      phone_num || existing.phone_num,
      cadre || existing.cadre,
      hashedPin,
      staff_id,
    ]);

    const [updatedRows] = await db.execute(
      `SELECT staff_id, firstName, lastName, email, phone_num, address, cadre FROM staffs WHERE staff_id = ? LIMIT 1`,
      [staff_id]
    );

    res.status(200).json({
      status: "success",
      message: `Staff profile with ID ${staff_id} updated successfully.`,
      updatedUser: updatedRows[0],
    });
  } catch (error) {
    next(error);
  }
};

module.exports = { updateProfile };
// This module handles updating staff profiles in the database.
// It validates the input, hashes the secret PIN if provided, and updates the staff record.
