import fs from 'fs';
import path from 'path';
import pool from '../config/db.js';

let tableChecked = false;

// Ensure promotions table exists in MySQL database
async function ensurePromotionsTable() {
  if (tableChecked) return;
  try {
    // Copy the generated promo image into the backend uploads directory if present
    try {
      const generatedImgPath = 'C:\\Users\\sakirul\\.gemini\\antigravity-ide\\brain\\7c9a850b-b50a-4130-94ab-a86e7c4688fe\\promo_popup_banner_1788339819098.jpg';
      const uploadsDir = path.join(process.cwd(), 'uploads');
      if (!fs.existsSync(uploadsDir)) {
        fs.mkdirSync(uploadsDir, { recursive: true });
      }
      const destPath = path.join(uploadsDir, 'promo_popup_banner.jpg');
      if (fs.existsSync(generatedImgPath) && !fs.existsSync(destPath)) {
        fs.copyFileSync(generatedImgPath, destPath);
      }
    } catch (copyErr) {
      console.warn("Could not copy generated banner:", copyErr.message);
    }

    await pool.query(`
      CREATE TABLE IF NOT EXISTS promotions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) DEFAULT 'Reach thousands of local customers in the halal community.',
        headline VARCHAR(255) NULL,
        image_url TEXT NOT NULL,
        images JSON NULL,
        button_text VARCHAR(100) DEFAULT 'Add Your Promotion Here',
        button_url VARCHAR(255) DEFAULT '#/add-listing',
        display_order INT DEFAULT 0,
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_promotions_active (is_active),
        INDEX idx_promotions_order (display_order)
      ) ENGINE=InnoDB;
    `);

    // Ensure images column exists for existing tables
    try {
      await pool.query(`ALTER TABLE promotions ADD COLUMN IF NOT EXISTS images JSON NULL`);
    } catch (e) {}

    tableChecked = true;
  } catch (err) {
    console.error("ensurePromotionsTable error:", err.message);
  }
}

// GET /api/promotions - Retrieve active promotions with multi-image support
export async function getActivePromotions(req, res) {
  try {
    await ensurePromotionsTable();

    const [rows] = await pool.query(`
      SELECT 
        id, 
        title, 
        headline, 
        image_url, 
        images, 
        button_text, 
        button_url, 
        display_order
      FROM promotions 
      WHERE is_active = TRUE 
      ORDER BY display_order ASC, id ASC
    `);

    // Normalize promotions & extract multi-image array
    const promotions = rows.map(item => {
      let imageList = [];
      if (item.images) {
        try {
          imageList = typeof item.images === 'string' ? JSON.parse(item.images) : item.images;
        } catch (e) {
          imageList = [];
        }
      }
      if (!Array.isArray(imageList) || imageList.length === 0) {
        imageList = item.image_url ? [item.image_url] : [];
      }

      return {
        id: item.id,
        title: item.title || "",
        headline: item.headline || "",
        image_url: item.image_url,
        images: imageList,
        button_text: item.button_text || "Learn More",
        button_url: item.button_url || "#/add-listing"
      };
    });

    return res.json({
      success: true,
      count: promotions.length,
      promotions
    });
  } catch (err) {
    console.error("getActivePromotions error:", err);
    return res.json({
      success: true,
      count: 0,
      promotions: []
    });
  }
}

// POST /api/promotions - Create a new promotion
export async function createPromotion(req, res) {
  try {
    await ensurePromotionsTable();
    const { title, headline, image_url, images, button_text, button_url, display_order } = req.body;

    if (!image_url && (!images || images.length === 0)) {
      return res.status(400).json({ error: "At least one promotional image is required." });
    }

    const primaryImg = image_url || (Array.isArray(images) ? images[0] : "");
    const imagesJson = Array.isArray(images) ? JSON.stringify(images) : JSON.stringify([primaryImg]);

    const [result] = await pool.query(
      `INSERT INTO promotions (title, headline, image_url, images, button_text, button_url, display_order, is_active)
       VALUES (?, ?, ?, ?, ?, ?, ?, TRUE)`,
      [
        title || "Reach thousands of local customers in the halal community.",
        headline || "",
        primaryImg,
        imagesJson,
        button_text || "Add Your Promotion Here",
        button_url || "#/add-listing",
        parseInt(display_order, 10) || 0
      ]
    );

    return res.status(201).json({
      success: true,
      promotionId: result.insertId,
      message: "Promotion created successfully."
    });
  } catch (err) {
    console.error("createPromotion error:", err);
    return res.status(500).json({ error: "Failed to create promotion." });
  }
}

// PUT /api/promotions/:id - Update existing promotion
export async function updatePromotion(req, res) {
  try {
    await ensurePromotionsTable();
    const promoId = parseInt(req.params.id, 10);
    const { title, headline, image_url, images, button_text, button_url, display_order, is_active } = req.body;

    const fields = [];
    const values = [];

    if (title !== undefined) { fields.push('title = ?'); values.push(title); }
    if (headline !== undefined) { fields.push('headline = ?'); values.push(headline); }
    if (image_url !== undefined) { fields.push('image_url = ?'); values.push(image_url); }
    if (images !== undefined) { fields.push('images = ?'); values.push(JSON.stringify(images)); }
    if (button_text !== undefined) { fields.push('button_text = ?'); values.push(button_text); }
    if (button_url !== undefined) { fields.push('button_url = ?'); values.push(button_url); }
    if (display_order !== undefined) { fields.push('display_order = ?'); values.push(display_order); }
    if (is_active !== undefined) { fields.push('is_active = ?'); values.push(is_active); }

    if (fields.length === 0) {
      return res.status(400).json({ error: "No fields provided to update." });
    }

    values.push(promoId);
    await pool.query(`UPDATE promotions SET ${fields.join(', ')} WHERE id = ?`, values);

    return res.json({ success: true, message: "Promotion updated successfully." });
  } catch (err) {
    console.error("updatePromotion error:", err);
    return res.status(500).json({ error: "Failed to update promotion." });
  }
}

// DELETE /api/promotions/:id - Remove a promotion
export async function deletePromotion(req, res) {
  try {
    await ensurePromotionsTable();
    const promoId = parseInt(req.params.id, 10);
    await pool.query(`DELETE FROM promotions WHERE id = ?`, [promoId]);
    return res.json({ success: true, message: "Promotion deleted successfully." });
  } catch (err) {
    console.error("deletePromotion error:", err);
    return res.status(500).json({ error: "Failed to delete promotion." });
  }
}
