-- Fixed version of handle_paid_order with hardcoded URL
-- Run this in Supabase SQL Editor

CREATE OR REPLACE FUNCTION handle_paid_order()
RETURNS TRIGGER AS $$
DECLARE
  edge_function_url TEXT;
  order_data JSON;
BEGIN
  -- Only proceed if payment_status changed to 'paid'
  IF (NEW.payment_status != 'paid' OR OLD.payment_status = 'paid') THEN
    RETURN NEW;
  END IF;

  -- Log the payment event
  RAISE NOTICE 'Order % payment status changed to paid', NEW.id;

  -- Hardcoded edge function URL
  edge_function_url := 'https://lovable.backoffice.biz.id/functions/v1/handle-order-paid';

  -- Prepare order data
  order_data := json_build_object(
    'order_id', NEW.id,
    'user_id', NEW.user_id,
    'total_amount', NEW.total_amount,
    'payment_method', NEW.payment_method,
    'payment_provider', NEW.payment_provider
  );

  -- Call the edge function asynchronously via pg_net
  PERFORM net.http_post(
    url := edge_function_url,
    headers := json_build_object(
      'Content-Type', 'application/json',
      'Authorization', 'Bearer ' || current_setting('app.service_role_key', true)
    ),
    body := order_data,
    timeout_milliseconds := 10000
  );

  RAISE NOTICE 'Called handle-order-paid for order %', NEW.id;

  RETURN NEW;
EXCEPTION
  WHEN OTHERS THEN
    -- Log error but don't fail the transaction
    RAISE WARNING 'Failed to call handle-order-paid for order %: %', NEW.id, SQLERRM;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;
