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

/* ===========================
   ✅ GET ALL SMTP CONFIGURATIONS
   GET /api/organization/:orgId/smtp-configs
=========================== */
const getSmtpConfigs = async (req, res) => {
  try {
    const { orgId } = req.params;

    // Check if table exists, create if not
    await ensureSmtpTable();

    const result = await pool.query(
      `SELECT * FROM organization_smtp_configs 
       WHERE org_id = $1 AND is_deleted = false 
       ORDER BY is_default DESC, created_at DESC`,
      [orgId]
    );

    res.json({ success: true, data: result.rows });
  } catch (error) {
    console.error("GET SMTP CONFIGS ERROR:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

/* ===========================
   ✅ CREATE SMTP CONFIGURATION
   POST /api/organization/:orgId/smtp-configs
=========================== */
const createSmtpConfig = async (req, res) => {
  try {
    const { orgId } = req.params;
    const userId = req.user?.id;
    const {
      name, host, port, encryption, username, password,
      from_email, from_name, reply_to, cc, bcc,
      auth_enabled, is_active, is_default
    } = req.body;

    // Validate required fields
    if (!name || !host || !from_email) {
      return res.status(400).json({
        success: false,
        message: "Name, host, and from_email are required"
      });
    }

    await ensureSmtpTable();

    // If this is default, unset other defaults
    if (is_default) {
      await pool.query(
        `UPDATE organization_smtp_configs 
         SET is_default = false WHERE org_id = $1`,
        [orgId]
      );
    }

    // If this is active and no other active, make it active
    let finalIsActive = is_active;
    if (is_active) {
      const activeCount = await pool.query(
        `SELECT COUNT(*) FROM organization_smtp_configs 
         WHERE org_id = $1 AND is_active = true AND is_deleted = false`,
        [orgId]
      );
      if (parseInt(activeCount.rows[0].count) === 0) {
        finalIsActive = true;
      }
    }

    const result = await pool.query(
      `INSERT INTO organization_smtp_configs (
        org_id, name, host, port, encryption, username, password,
        from_email, from_name, reply_to, cc, bcc,
        auth_enabled, is_active, is_default, created_by, updated_by
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $16)
      RETURNING *`,
      [
        orgId, name, host, port || 587, encryption || 'TLS',
        username || null, password || null,
        from_email, from_name || null, reply_to || null, cc || null, bcc || null,
        auth_enabled !== false, finalIsActive !== false, is_default || false,
        userId
      ]
    );

    // Don't return password in response
    const { password: _, ...config } = result.rows[0];
    res.status(201).json({ success: true, data: config });
  } catch (error) {
    console.error("CREATE SMTP CONFIG ERROR:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

/* ===========================
   ✅ UPDATE SMTP CONFIGURATION
   PUT /api/organization/:orgId/smtp-configs/:id
=========================== */
const updateSmtpConfig = async (req, res) => {
  try {
    const { orgId, id } = req.params;
    const userId = req.user?.id;
    const {
      name, host, port, encryption, username, password,
      from_email, from_name, reply_to, cc, bcc,
      auth_enabled, is_active, is_default
    } = req.body;

    await ensureSmtpTable();

    // If this is default, unset other defaults
    if (is_default) {
      await pool.query(
        `UPDATE organization_smtp_configs 
         SET is_default = false WHERE org_id = $1 AND id != $2`,
        [orgId, id]
      );
    }

    const result = await pool.query(
      `UPDATE organization_smtp_configs SET
        name = COALESCE($1, name),
        host = COALESCE($2, host),
        port = COALESCE($3, port),
        encryption = COALESCE($4, encryption),
        username = COALESCE($5, username),
        password = COALESCE($6, password),
        from_email = COALESCE($7, from_email),
        from_name = COALESCE($8, from_name),
        reply_to = COALESCE($9, reply_to),
        cc = COALESCE($10, cc),
        bcc = COALESCE($11, bcc),
        auth_enabled = COALESCE($12, auth_enabled),
        is_active = COALESCE($13, is_active),
        is_default = COALESCE($14, is_default),
        updated_by = $15,
        updated_at = NOW()
      WHERE id = $16 AND org_id = $17 AND is_deleted = false
      RETURNING *`,
      [
        name, host, port, encryption, username, password,
        from_email, from_name, reply_to, cc, bcc,
        auth_enabled, is_active, is_default,
        userId, id, orgId
      ]
    );

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

    const { password: _, ...config } = result.rows[0];
    res.json({ success: true, data: config });
  } catch (error) {
    console.error("UPDATE SMTP CONFIG ERROR:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

/* ===========================
   ✅ DELETE SMTP CONFIGURATION
   DELETE /api/organization/:orgId/smtp-configs/:id
=========================== */
const deleteSmtpConfig = async (req, res) => {
  try {
    const { orgId, id } = req.params;
    const userId = req.user?.id;

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

    res.json({ success: true, message: "SMTP configuration deleted" });
  } catch (error) {
    console.error("DELETE SMTP CONFIG ERROR:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

/* ===========================
   ✅ TEST SMTP CONNECTION
   POST /api/organization/:orgId/smtp-configs/:id/test
=========================== */
const testSmtpConnection = async (req, res) => {
  try {
    const { orgId, id } = req.params;
    
    // Get the config
    const result = await pool.query(
      `SELECT * FROM organization_smtp_configs 
       WHERE id = $1 AND org_id = $2 AND is_deleted = false`,
      [id, orgId]
    );

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

    const config = result.rows[0];

    // Here you would implement actual SMTP test using nodemailer
    // For now, return success
    res.json({ success: true, message: "Test connection successful" });
  } catch (error) {
    console.error("TEST SMTP ERROR:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

/* ===========================
   ✅ TOGGLE SMTP ACTIVE STATUS
   PATCH /api/organization/:orgId/smtp-configs/:id
=========================== */
const toggleSmtpActive = async (req, res) => {
  try {
    const { orgId, id } = req.params;
    const { is_active } = req.body;

    const result = await pool.query(
      `UPDATE organization_smtp_configs 
       SET is_active = $1, updated_at = NOW()
       WHERE id = $2 AND org_id = $3 AND is_deleted = false
       RETURNING *`,
      [is_active, id, orgId]
    );

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

    res.json({ success: true, data: result.rows[0] });
  } catch (error) {
    console.error("TOGGLE SMTP ERROR:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

/* ===========================
   ✅ SET AS DEFAULT
   PATCH /api/organization/:orgId/smtp-configs/:id/set-default
=========================== */
const setAsDefault = async (req, res) => {
  try {
    const { orgId, id } = req.params;

    // Unset all defaults
    await pool.query(
      `UPDATE organization_smtp_configs 
       SET is_default = false WHERE org_id = $1`,
      [orgId]
    );

    // Set this as default
    const result = await pool.query(
      `UPDATE organization_smtp_configs 
       SET is_default = true, updated_at = NOW()
       WHERE id = $1 AND org_id = $2 AND is_deleted = false
       RETURNING *`,
      [id, orgId]
    );

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

    res.json({ success: true, data: result.rows[0] });
  } catch (error) {
    console.error("SET DEFAULT SMTP ERROR:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

// Helper function to ensure table exists
async function ensureSmtpTable() {
  await pool.query(`
    CREATE TABLE IF NOT EXISTS organization_smtp_configs (
      id SERIAL PRIMARY KEY,
      org_id INTEGER NOT NULL REFERENCES organizations(id),
      name VARCHAR(100) NOT NULL,
      host VARCHAR(255) NOT NULL,
      port INTEGER DEFAULT 587,
      encryption VARCHAR(20) DEFAULT 'TLS',
      username VARCHAR(255),
      password TEXT,
      from_email VARCHAR(255) NOT NULL,
      from_name VARCHAR(255),
      reply_to VARCHAR(255),
      cc TEXT,
      bcc TEXT,
      auth_enabled BOOLEAN DEFAULT true,
      is_active BOOLEAN DEFAULT true,
      is_default BOOLEAN DEFAULT false,
      is_deleted BOOLEAN DEFAULT false,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
      created_by INTEGER,
      updated_by INTEGER
    );
  `);
}

module.exports = {
  getSmtpConfigs,
  createSmtpConfig,
  updateSmtpConfig,
  deleteSmtpConfig,
  testSmtpConnection,
  toggleSmtpActive,
  setAsDefault,
};