const db = require("../../managers/dbConfig");
const generateLicenseKey = require("../../managers/generateLicenseKey");
const logger = require("../../handlers/logger");

// Get License by Hospital ID
exports.getLicense = async (hospital_id) => {
  const [rows] = await db.execute(
    "SELECT * FROM licenses WHERE hospital_id = ?",
    [hospital_id]
  );
  return rows[0] || null;
};

// Renew License
exports.renewLicense = async (hospitalId) => {
  const connection = await db.getConnection();
  await connection.beginTransaction();

  try {
    // Fetch current plan details
    const [plans] = await connection.query(
      `SELECT sp.duration, sp.price, w.balance
             FROM subscription_plans sp
             JOIN hosp_setting hs ON hs.plan_id = sp.id
             JOIN wallets w ON w.hospital_id = hs.id
             WHERE hs.id = ?`,
      [hospitalId]
    );

    if (!plans || plans.length === 0) {
      throw "Subscription plan not found";
    }

    const { duration, price, balance } = plans[0];

    if (balance < price) {
      throw "Insufficient funds in wallet";
    }

    // Deduct amount from wallet
    const newBalance = balance - price;
    await connection.query(
      `UPDATE wallets SET balance = ? WHERE hospital_id = ?`,
      [newBalance, hospitalId]
    );

    // Log transaction
    await connection.query(
      `INSERT INTO wallet_transactions 
             (hospital_id, transaction_type, amount, balance_before, balance_after, description)
             VALUES (?, 'debit', ?, ?, ?, 'License renewal')`,
      [hospitalId, price, balance, newBalance]
    );

    // Generate new license key
    const newLicenseKey = generateLicenseKey();

    // Update license expiry date
    await connection.query(
      `UPDATE licenses 
             SET license_key = ?, expiry_date = DATE_ADD(NOW(), INTERVAL ? DAY) 
             WHERE hospital_id = ?`,
      [newLicenseKey, duration, hospitalId]
    );

    await connection.commit();

    logger.info(
      `License renewed for hospital ${hospitalId}. New key: ${newLicenseKey}`
    );

    return {
      status: "success",
      message: "License renewed successfully",
      newLicenseKey,
    };
  } catch (error) {
    await connection.rollback();

    logger.error(
      `License renewal failed for hospital ${hospitalId}: ${error.message}`
    );

    return { status: "failed", message: error.message };
  } finally {
    connection.release();
  }
};

// Reset License (Admin action)
exports.resetLicense = async (hospital_id, new_machine_id) => {
  await db.execute("UPDATE licenses SET machine_id = ? WHERE hospital_id = ?", [
    new_machine_id,
    hospital_id,
  ]);
};
