import { pool } from "../config/db.js";

const STANDARD_PAYMENT_METHODS = [
  { name: "Efectivo", code: "cash" },
  { name: "Ath Movil", code: "ath_movil" },
  { name: "Visa", code: "visa" },
  { name: "Mastercard", code: "mastercard" },
  { name: "Amex", code: "amex" },
  { name: "Otro", code: "other" }
];

async function ensureStandardPaymentMethods() {
  for (const method of STANDARD_PAYMENT_METHODS) {
    await pool.query(
      `
      INSERT INTO payment_methods (name, code, is_active)
      VALUES (:name, :code, 1)
      ON DUPLICATE KEY UPDATE name = VALUES(name), is_active = 1
      `,
      method
    );
  }

  await pool.query("UPDATE payment_methods SET is_active = 0 WHERE code = 'card'");
}

export async function getPaymentMethods(req, res, next) {
  try {
    await ensureStandardPaymentMethods();
    const [rows] = await pool.query(`
      SELECT *
      FROM payment_methods
      ORDER BY is_active DESC, FIELD(code, 'cash', 'ath_movil', 'visa', 'mastercard', 'amex', 'other'), id ASC
    `);
    res.json({
      success: true,
      data: rows.map(r => ({
        id: r.id,
        name: r.name,
        code: r.code,
        isActive: Boolean(r.is_active)
      }))
    });
  } catch (err) {
    next(err);
  }
}

export async function createPaymentMethod(req, res, next) {
  try {
    const { name } = req.body;
    if (!name || !name.trim()) {
      return res.status(400).json({
        success: false,
        message: "El nombre del método de pago es requerido"
      });
    }
    const code = name.trim().toLowerCase().replace(/[^a-z0-9]/g, "_");

    const [result] = await pool.query(
      `INSERT INTO payment_methods (name, code, is_active)
       VALUES (:name, :code, 1)`,
      { name: name.trim(), code }
    );

    res.status(201).json({
      success: true,
      message: "Método de pago creado correctamente",
      data: {
        id: result.insertId,
        name: name.trim(),
        code,
        isActive: true
      }
    });
  } catch (err) {
    if (err.code === "ER_DUP_ENTRY") {
      return res.status(400).json({
        success: false,
        message: "Este método de pago ya existe"
      });
    }
    next(err);
  }
}

export async function deletePaymentMethod(req, res, next) {
  try {
    const { id } = req.params;
    const [existing] = await pool.query("SELECT id, code FROM payment_methods WHERE id = ?", [id]);
    if (!existing.length) {
      return res.status(404).json({
        success: false,
        message: "Método de pago no encontrado"
      });
    }

    // Check if there are transactions referencing this payment method
    const [paymentsCount] = await pool.query("SELECT COUNT(*) AS count FROM payments WHERE method = ?", [existing[0].code]);
    if (paymentsCount[0].count > 0) {
      // Soft-delete: deactivate it so it won't show in new lists but exists in old orders
      await pool.query("UPDATE payment_methods SET is_active = 0 WHERE id = ?", [id]);
      res.json({
        success: true,
        message: "Método de pago desactivado correctamente"
      });
    } else {
      // Hard delete: remove completely since no transaction uses it
      await pool.query("DELETE FROM payment_methods WHERE id = ?", [id]);
      res.json({
        success: true,
        message: "Método de pago eliminado correctamente"
      });
    }
  } catch (err) {
    next(err);
  }
}
