import db from "../src/models/index.js";
import CustomerController from "../src/controllers/customerController.js";

/**
 * MERCHANT CREDIT VERIFICATION SCRIPT
 * This script tests the internal credit logic using mock req/res.
 */

async function verifyMerchantCredit() {
  console.log("🏁 Starting Merchant Credit Verification...");
  const { Merchant, Customer, Transaction, sequelize } = db;

  try {
    // 1. Setup Mock Data
    const merchant = await Merchant.create({
      businessName: "Test Merchant",
      email: `test-${Date.now()}@example.com`,
      password: "password",
      balance: 5000.00
    });

    const customer = await Customer.create({
      merchantId: merchant.id,
      fullName: "Test Customer",
      email: `cust-${Date.now()}@example.com`,
      balance: 100.00
    });

    console.log(`Initial Balances -> Merchant: ${merchant.balance}, Customer: ${customer.balance}`);

    // 2. Mock Request & Response
    const amountToCredit = 1000.00;
    const req = {
      params: { customerId: customer.id },
      merchant: { id: merchant.id },
      body: { 
        amount: amountToCredit, 
        narration: "Verification Credit" 
      }
    };

    let responseData = null;
    const res = {
      status: (code) => ({
        json: (data) => {
          responseData = data;
          console.log(`📡 Response [${code}]:`, data.message || data);
        }
      })
    };

    // 3. Execute Credit
    await CustomerController.creditCustomer(req, res);

    // 4. Verify Results
    const updatedMerchant = await Merchant.findByPk(merchant.id);
    const updatedCustomer = await Customer.findByPk(customer.id);
    const tx = await Transaction.findOne({ where: { customerId: customer.id, class: "merchant_credit" } });

    console.log("-----------------------------------------");
    console.log(`Final Balances -> Merchant: ${updatedMerchant.balance}, Customer: ${updatedCustomer.balance}`);
    
    const success = 
      parseFloat(updatedMerchant.balance) === 4000.00 && 
      parseFloat(updatedCustomer.balance) === 1100.00 &&
      tx !== null;

    if (success) {
      console.log("🏆 SUCCESS: Merchant credit logic verified!");
    } else {
      console.error("❌ FAILURE: Balance mismatch or transaction missing.");
    }
    console.log("-----------------------------------------");

    // 5. Cleanup
    await tx?.destroy();
    await customer.destroy();
    await merchant.destroy();

  } catch (error) {
    console.error("❌ Verification Error:", error.message);
  } finally {
    // Note: In a real test we wouldn't exit process, but this is a standalone verification script
    process.exit();
  }
}

verifyMerchantCredit();
