-- RPC: rpc_admin_save_delivery_station
-- 管理端新增或更新提货点/核销点信息

CREATE OR REPLACE FUNCTION public.rpc_admin_save_delivery_station(
    p_id UUID DEFAULT NULL,
    p_name TEXT DEFAULT NULL,
    p_phone TEXT DEFAULT NULL,
    p_address TEXT DEFAULT NULL,
    p_image TEXT DEFAULT NULL,
    p_lng NUMERIC DEFAULT NULL,
    p_lat NUMERIC DEFAULT NULL,
    p_status SMALLINT DEFAULT 1,
    p_sort_order INTEGER DEFAULT 0,
    p_business_hours JSONB DEFAULT NULL
)
RETURNS UUID
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_id UUID;
BEGIN
    -- 1. 权限检查 (仅管理员)
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE auth_id = auth.uid() AND role = 'admin'
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 参数校验
    IF p_name IS NULL OR p_phone IS NULL OR p_address IS NULL THEN
        RAISE EXCEPTION 'Missing required fields: name, phone or address';
    END IF;

    -- 3. 新增或更新
    IF p_id IS NULL THEN
        INSERT INTO public.ml_delivery_stations (
            name, phone, address, image, lng, lat, status, sort_order, business_hours
        ) VALUES (
            p_name, p_phone, p_address, p_image, p_lng, p_lat, p_status, p_sort_order, p_business_hours
        ) RETURNING id INTO v_id;
    ELSE
        UPDATE public.ml_delivery_stations
        SET 
            name = COALESCE(p_name, name),
            phone = COALESCE(p_phone, phone),
            address = COALESCE(p_address, address),
            image = COALESCE(p_image, image),
            lng = COALESCE(p_lng, lng),
            lat = COALESCE(p_lat, lat),
            status = COALESCE(p_status, status),
            sort_order = COALESCE(p_sort_order, sort_order),
            business_hours = COALESCE(p_business_hours, business_hours),
            updated_at = now()
        WHERE id = p_id
        RETURNING id INTO v_id;

        IF v_id IS NULL THEN
            RAISE EXCEPTION 'Station not found';
        END IF;
    END IF;

    RETURN v_id;
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_save_delivery_station(UUID, TEXT, TEXT, TEXT, TEXT, NUMERIC, NUMERIC, SMALLINT, INTEGER, JSONB) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_save_delivery_station(UUID, TEXT, TEXT, TEXT, TEXT, NUMERIC, NUMERIC, SMALLINT, INTEGER, JSONB) TO authenticated;
