-- ============================================================================
-- Order Deletion Function
-- ============================================================================
-- Safely deletes an order and all related data in the correct sequence
-- to maintain database integrity and avoid orphaned records.
-- ============================================================================

CREATE OR REPLACE FUNCTION delete_order(order_uuid UUID)
RETURNS JSON AS $$
DECLARE
  order_user_id UUID;
  order_payment_status TEXT;
  deleted_counts JSON;
BEGIN
  -- Get order details first
  SELECT user_id, payment_status
  INTO order_user_id, order_payment_status
  FROM orders
  WHERE id = order_uuid;

  IF NOT FOUND THEN
    RETURN jsonb_build_object(
      'success', false,
      'error', 'Order not found'
    );
  END IF;

  -- Log the deletion
  RAISE NOTICE 'Deleting order: %', order_uuid;

  -- Step 1: Delete consulting-related reviews
  DELETE FROM reviews
  WHERE order_id = order_uuid
  AND type = 'consulting';
  RAISE NOTICE 'Deleted consulting reviews for order %', order_uuid;

  -- Step 2: Delete consulting slots (this also removes meet_link references)
  DELETE FROM consulting_slots
  WHERE order_id = order_uuid;
  RAISE NOTICE 'Deleted consulting slots for order %', order_uuid;

  -- Step 3: Delete order items
  DELETE FROM order_items
  WHERE order_id = order_uuid;
  RAISE NOTICE 'Deleted order items for order %', order_uuid;

  -- Step 4: Delete user access records (only if order was paid)
  IF order_payment_status = 'paid' THEN
    DELETE FROM user_access
    WHERE user_id = order_user_id
    AND product_id IN (
      SELECT product_id FROM order_items WHERE order_id = order_uuid
    );
    RAISE NOTICE 'Deleted user access for order %', order_uuid;
  END IF;

  -- Step 5: Finally delete the order itself
  DELETE FROM orders
  WHERE id = order_uuid;
  RAISE NOTICE 'Deleted order %', order_uuid;

  -- Build success response with counts
  deleted_counts := jsonb_build_object(
    'success', true,
    'order_id', order_uuid,
    'message', 'Order and all related data deleted successfully'
  );

  RETURN deleted_counts;
EXCEPTION
  WHEN OTHERS THEN
    RETURN jsonb_build_object(
      'success', false,
      'error', SQLERRM,
      'detail', 'Failed to delete order: ' || order_uuid
    );
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Grant execute permission
GRANT EXECUTE ON FUNCTION delete_order(UUID) TO postgres;
GRANT EXECUTE ON FUNCTION delete_order(UUID) TO authenticated;

-- Add comment
COMMENT ON FUNCTION delete_order(UUID) IS 'Safely deletes an order and all related data (reviews, consulting slots, order items, user access) in the correct sequence to maintain data integrity.';
