-- RPC: rpc_admin_save_role
-- 管理端新增或更新角色

CREATE OR REPLACE FUNCTION public.rpc_admin_save_role(
    p_id UUID DEFAULT NULL,
    p_name TEXT DEFAULT NULL,
    p_code TEXT DEFAULT NULL,
    p_description TEXT DEFAULT NULL,
    p_is_active 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_roles (
            name, code, description, is_active
        ) VALUES (
            p_name, p_code, p_description, p_is_active
        ) RETURNING id INTO v_id;
    ELSE
        -- 3. 更新
        UPDATE public.ak_roles
        SET 
            name = COALESCE(p_name, name),
            code = COALESCE(p_code, code),
            description = COALESCE(p_description, description),
            is_active = COALESCE(p_is_active, is_active),
            updated_at = now()
        WHERE id = p_id
        RETURNING id INTO v_id;

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

    RETURN v_id;
END;
$$;

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