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

// ========================
// SECTIONS CRUD
// ========================

// Get all sections
const getAllSections = async (req, res) => {
  try {
    const orgId = req.user?.orgId;
    if (!orgId) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }

    const result = await pool.query(
      `SELECT id, name, default_content FROM terms_sections 
       WHERE org_id = $1 AND is_deleted = false 
       ORDER BY id ASC`,
      [orgId]
    );

    res.json({ success: true, data: result.rows });
  } catch (err) {
    console.error("Error in getAllSections:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

// Add new section
const addSection = async (req, res) => {
  try {
    const orgId = req.user?.orgId;
    const userId = req.user?.userId || req.user?.email;
    const { name, defaultContent } = req.body;

    if (!orgId) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }
    if (!name) {
      return res.status(400).json({ success: false, message: "Section name required" });
    }

    const result = await pool.query(
      `INSERT INTO terms_sections (name, default_content, org_id, created_by, updated_by)
       VALUES ($1, $2, $3, $4, $5)
       RETURNING id, name, default_content`,
      [name, defaultContent || "", orgId, userId, userId]
    );

    res.status(201).json({ success: true, data: result.rows[0] });
  } catch (err) {
    console.error("Error in addSection:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

// Update section
const updateSection = async (req, res) => {
  try {
    const { id } = req.params;
    const orgId = req.user?.orgId;
    const userId = req.user?.userId || req.user?.email;
    const { name, defaultContent } = req.body;

    if (!orgId) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }

    const result = await pool.query(
      `UPDATE terms_sections 
       SET name = $1, default_content = $2, updated_by = $3, updated_at = NOW()
       WHERE id = $4 AND org_id = $5 AND is_deleted = false
       RETURNING id, name, default_content`,
      [name, defaultContent || "", userId, parseInt(id), orgId]
    );

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

    res.json({ success: true, data: result.rows[0] });
  } catch (err) {
    console.error("Error in updateSection:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

// Delete section
const deleteSection = async (req, res) => {
  try {
    const { id } = req.params;
    const orgId = req.user?.orgId;
    const userId = req.user?.userId || req.user?.email;

    if (!orgId) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }

    const result = await pool.query(
      `UPDATE terms_sections 
       SET is_deleted = true, updated_by = $1, updated_at = NOW()
       WHERE id = $2 AND org_id = $3 AND is_deleted = false
       RETURNING id`,
      [userId, parseInt(id), orgId]
    );

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

    res.json({ success: true, message: "Section deleted successfully" });
  } catch (err) {
    console.error("Error in deleteSection:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

// ========================
// TEMPLATES CRUD
// ========================

// Get all templates by module
const getAllTemplates = async (req, res) => {
  try {
    const orgId = req.user?.orgId;
    const { module_type = "purchase_order" } = req.query;

    if (!orgId) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }

    const result = await pool.query(
      `SELECT id, name, is_default, selected_sections, section_contents, module_type, status
       FROM terms_conditions 
       WHERE org_id = $1 AND module_type = $2 AND is_deleted = false 
       ORDER BY is_default DESC, id ASC`,
      [orgId, module_type]
    );

    const templates = result.rows.map(row => ({
      id: row.id,
      name: row.name,
      isDefault: row.is_default,
      selectedSections: row.selected_sections || [],
      sectionContents: row.section_contents || {},
      moduleType: row.module_type,
      status: row.status
    }));

    res.json({ success: true, data: templates });
  } catch (err) {
    console.error("Error in getAllTemplates:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

// Add new template
const addTemplate = async (req, res) => {
  try {
    const orgId = req.user?.orgId;
    const userId = req.user?.userId || req.user?.email;
    const { name, isDefault, selectedSections, sectionContents, moduleType } = req.body;

    if (!orgId) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }
    if (!name) {
      return res.status(400).json({ success: false, message: "Template name required" });
    }

    // If this template is default, remove default from other templates in same module
    if (isDefault) {
      await pool.query(
        `UPDATE terms_conditions 
         SET is_default = false 
         WHERE org_id = $1 AND module_type = $2 AND is_deleted = false`,
        [orgId, moduleType]
      );
    }

    const result = await pool.query(
      `INSERT INTO terms_conditions 
        (name, is_default, selected_sections, section_contents, module_type, org_id, created_by, updated_by)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
       RETURNING id, name, is_default, selected_sections, section_contents, module_type`,
      [name, isDefault || false, JSON.stringify(selectedSections || []), JSON.stringify(sectionContents || {}), moduleType, orgId, userId, userId]
    );

    res.status(201).json({ success: true, data: result.rows[0] });
  } catch (err) {
    console.error("Error in addTemplate:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

// Update template
const updateTemplate = async (req, res) => {
  try {
    const { id } = req.params;
    const orgId = req.user?.orgId;
    const userId = req.user?.userId || req.user?.email;
    const { name, isDefault, selectedSections, sectionContents, moduleType } = req.body;

    if (!orgId) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }

    // If this template is default, remove default from other templates in same module
    if (isDefault) {
      await pool.query(
        `UPDATE terms_conditions 
         SET is_default = false 
         WHERE org_id = $1 AND module_type = $2 AND id != $3 AND is_deleted = false`,
        [orgId, moduleType, parseInt(id)]
      );
    }

    const result = await pool.query(
      `UPDATE terms_conditions 
       SET name = $1, is_default = $2, selected_sections = $3, section_contents = $4, 
           updated_by = $5, updated_at = NOW()
       WHERE id = $6 AND org_id = $7 AND is_deleted = false
       RETURNING id, name, is_default, selected_sections, section_contents, module_type`,
      [name, isDefault || false, JSON.stringify(selectedSections || []), JSON.stringify(sectionContents || {}), userId, parseInt(id), orgId]
    );

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

    res.json({ success: true, data: result.rows[0] });
  } catch (err) {
    console.error("Error in updateTemplate:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

// Delete template
const deleteTemplate = async (req, res) => {
  try {
    const { id } = req.params;
    const orgId = req.user?.orgId;
    const userId = req.user?.userId || req.user?.email;

    if (!orgId) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }

    const result = await pool.query(
      `UPDATE terms_conditions 
       SET is_deleted = true, updated_by = $1, updated_at = NOW()
       WHERE id = $2 AND org_id = $3 AND is_deleted = false
       RETURNING id`,
      [userId, parseInt(id), orgId]
    );

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

    res.json({ success: true, message: "Template deleted successfully" });
  } catch (err) {
    console.error("Error in deleteTemplate:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

// Set default template
const setDefaultTemplate = async (req, res) => {
  try {
    const { id } = req.params;
    const orgId = req.user?.orgId;
    const userId = req.user?.userId || req.user?.email;

    if (!orgId) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }

    // Get template to know its module type
    const templateResult = await pool.query(
      `SELECT module_type FROM terms_conditions WHERE id = $1 AND org_id = $2 AND is_deleted = false`,
      [parseInt(id), orgId]
    );

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

    const moduleType = templateResult.rows[0].module_type;

    // Remove default from all templates in same module
    await pool.query(
      `UPDATE terms_conditions 
       SET is_default = false 
       WHERE org_id = $1 AND module_type = $2 AND is_deleted = false`,
      [orgId, moduleType]
    );

    // Set this template as default
    await pool.query(
      `UPDATE terms_conditions 
       SET is_default = true, updated_by = $1, updated_at = NOW()
       WHERE id = $2 AND org_id = $3 AND is_deleted = false`,
      [userId, parseInt(id), orgId]
    );

    res.json({ success: true, message: "Default template updated" });
  } catch (err) {
    console.error("Error in setDefaultTemplate:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

module.exports = {
  getAllSections,
  addSection,
  updateSection,
  deleteSection,
  getAllTemplates,
  addTemplate,
  updateTemplate,
  deleteTemplate,
  setDefaultTemplate
};