-- RPC: rpc_admin_save_permission
-- 管理端新增或更新功能权限/菜单

CREATE OR REPLACE FUNCTION public.rpc_admin_save_permission(
    p_id UUID DEFAULT NULL,
    p_parent_id UUID DEFAULT NULL,
    p_name TEXT DEFAULT NULL,
    p_code TEXT DEFAULT NULL,
    p_type TEXT DEFAULT 'menu',
    p_path TEXT DEFAULT NULL,
    p_icon TEXT DEFAULT NULL,
    p_sort_order INTEGER DEFAULT 0,
    p_is_visible BOOLEAN DEFAULT TRUE
)
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_id IS NULL THEN
        IF p_name IS NULL OR p_code IS NULL THEN
            RAISE EXCEPTION 'Missing required fields: name or code';
        END IF;

        INSERT INTO public.ak_permissions (
            parent_id, name, code, type, path, icon, sort_order, is_visible
        ) VALUES (
            p_parent_id, p_name, p_code, p_type, p_path, p_icon, p_sort_order, p_is_visible
        ) RETURNING id INTO v_id;
    ELSE
        -- 3. 更新
        UPDATE public.ak_permissions
        SET 
            parent_id = COALESCE(p_parent_id, parent_id),
            name = COALESCE(p_name, name),
            code = COALESCE(p_code, code),
            type = COALESCE(p_type, type),
            path = COALESCE(p_path, path),
            icon = COALESCE(p_icon, icon),
            sort_order = COALESCE(p_sort_order, sort_order),
            is_visible = COALESCE(p_is_visible, is_visible),
            updated_at = now()
        WHERE id = p_id
        RETURNING id INTO v_id;

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

    RETURN v_id;
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_save_permission(UUID, UUID, TEXT, TEXT, TEXT, TEXT, TEXT, INTEGER, BOOLEAN) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_save_permission(UUID, UUID, TEXT, TEXT, TEXT, TEXT, TEXT, INTEGER, BOOLEAN) TO authenticated;
