const { createClient } = require("@supabase/supabase-js");
const crypto = require("crypto");

// Supabase configuration
const SUPABASE_URL = 
const SUPABASE_KEY = 
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);

// Credentials
const USERNAME = 
const PASSWORD = 
const SECRET_KEY = 

exports.handler = async (event) => {
  if (event.httpMethod === "OPTIONS") {
    return {
      statusCode: 204,
      headers: corsHeaders(),
    };
  }

  if (event.httpMethod !== "POST") {
    return {
      statusCode: 405,
      headers: corsHeaders(),
      body: JSON.stringify({ ResultCode: "1", ResultDesc: "Method Not Allowed" }),
    };
  }

  const contentType = (event.headers["content-type"] || "").toLowerCase();
  if (!contentType.includes("application/json")) {
    return {
      statusCode: 415,
      headers: corsHeaders(),
      body: JSON.stringify({ ResultCode: "1", ResultDesc: "Unsupported Media Type" }),
    };
  }

  try {
    const req = JSON.parse(event.body);
    console.log("📥 Incoming JSON payload:", req);

    // Credential check
    if (req.Username !== USERNAME || req.Password !== PASSWORD) {
      return {
        statusCode: 403,
        headers: corsHeaders(),
        body: JSON.stringify({ ResultCode: "1", ResultDesc: "Invalid credentials" }),
      };
    }

    // Hash verification
    const hashString = 
      SECRET_KEY +
      req.TransType +
      req.TransID +
      req.TransTime +
      req.TransAmount +
      req.BusinessShortCode +
      req.BillRefNumber +
      req.Mobile +
      req.name +
      "SUCCESS";

    const expectedHash = crypto.createHash("sha256").update(hashString).digest("base64");

    if (req.Hash !== expectedHash) {
      console.log("❌ Hash mismatch");
      return {
        statusCode: 400,
        headers: corsHeaders(),
        body: JSON.stringify({ ResultCode: "1", ResultDesc: "Invalid hash" }),
      };
    }

    // Insert into payments table
    const { error } = await supabase.from("payments").insert({
      adm_no: req.BillRefNumber,
      student_name: req.name,
      amount: parseFloat(req.TransAmount),
      phone_number: req.Mobile,
      mpesa_receipt: req.TransID,
      purpose: "MPESA Payment",
      payment_method: "mpesa",
      status: "completed",
      transaction_date: new Date(req.created_at).toISOString(),
    });

    if (error) {
      console.error("❌ Supabase error:", error);
      return {
        statusCode: 500,
        headers: corsHeaders(),
        body: JSON.stringify({ ResultCode: "1", ResultDesc: "Database error" }),
      };
    }

    return {
      statusCode: 200,
      headers: corsHeaders(),
      body: JSON.stringify({ ResultCode: "0", ResultDesc: "Payment recorded successfully" }),
    };
  } catch (err) {
    console.error("❌ Server error:", err);
    return {
      statusCode: 500,
      headers: corsHeaders(),
      body: JSON.stringify({ ResultCode: "1", ResultDesc: "Server error" }),
    };
  }
};

// CORS headers
function corsHeaders() {
  return {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "Content-Type",
    "Access-Control-Allow-Methods": "POST, OPTIONS",
    "Content-Type": "application/json",
  };
}
