const { pool } = require("../../config/db");

// Get all active module types (simple version)
const getModuleNames = async (req, res) => {
  try {
    const result = await pool.query(
      `
      SELECT 
        id,
        module_name,
        module_code,
        description,
        is_active
      FROM module_types
      WHERE is_active = true
      ORDER BY module_name ASC
      `
    );

    return res.status(200).json({
      success: true,
      data: result.rows,
      count: result.rows.length,
    });
  } catch (error) {
    console.error("Get Module Names Error:", error);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch module names",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

// Get only module names and codes (minimal version)
const getSimpleModuleNames = async (req, res) => {
  try {
    const result = await pool.query(
      `
      SELECT 
        id,
        module_name,
        module_code
      FROM module_types
      WHERE is_active = true
      ORDER BY module_name ASC
      `
    );

    return res.status(200).json({
      success: true,
      data: result.rows,
      count: result.rows.length,
    });
  } catch (error) {
    console.error("Get Simple Module Names Error:", error);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch module names",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

// Get module by ID (optional)
const getModuleById = async (req, res) => {
  try {
    const { id } = req.params;

    const result = await pool.query(
      `
      SELECT 
        id,
        module_name,
        module_code,
        description,
        is_active
      FROM module_types
      WHERE id = $1 AND is_active = true
      `,
      [id]
    );

    if (result.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: "Module not found",
      });
    }

    return res.status(200).json({
      success: true,
      data: result.rows[0],
    });
  } catch (error) {
    console.error("Get Module By ID Error:", error);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch module",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

module.exports = {
  getModuleNames,
  getSimpleModuleNames,
  getModuleById,
};