CREATE OR REPLACE FUNCTION medreport.get_latest_medipost_dispatch_state_for_order(medusa_order_id text)
RETURNS TABLE(has_success boolean, action_date timestamp with time zone) AS $$
SELECT 
    CASE 
        WHEN ma.has_error = false THEN true 
        ELSE false 
    END as has_success,
    ma.created_at as action_date
FROM medreport.medipost_actions ma
WHERE ma.medusa_order_id = $1
AND ma.action = 'send_order_to_medipost'
ORDER BY ma.created_at DESC
LIMIT 1;
$$ LANGUAGE sql STABLE;

grant execute on function medreport.get_latest_medipost_dispatch_state_for_order(text) to service_role;
