-- c77_rbac--1.1.0.sql: PostgreSQL extension for role-based access control (RBAC)
-- Requires PostgreSQL 14 or later
-- All objects in public schema with c77_rbac_ prefix
\echo Use "CREATE EXTENSION c77_rbac" to load this file. \quit

-- Tables
CREATE TABLE public.c77_rbac_subjects (
                                          subject_id BIGSERIAL PRIMARY KEY,
                                          external_id TEXT UNIQUE NOT NULL
);

CREATE TABLE public.c77_rbac_roles (
                                       role_id BIGSERIAL PRIMARY KEY,
                                       name TEXT UNIQUE NOT NULL
);

CREATE TABLE public.c77_rbac_features (
                                          feature_id BIGSERIAL PRIMARY KEY,
                                          name TEXT UNIQUE NOT NULL
);

CREATE TABLE public.c77_rbac_subject_roles (
                                               subject_id BIGINT REFERENCES public.c77_rbac_subjects(subject_id),
                                               role_id BIGINT REFERENCES public.c77_rbac_roles(role_id),
                                               scope_type TEXT NOT NULL,
                                               scope_id TEXT,
                                               PRIMARY KEY (subject_id, role_id, scope_type, scope_id)
);

CREATE TABLE public.c77_rbac_role_features (
                                               role_id BIGINT REFERENCES public.c77_rbac_roles(role_id),
                                               feature_id BIGINT REFERENCES public.c77_rbac_features(feature_id),
                                               PRIMARY KEY (role_id, feature_id)
);

-- Function: c77_rbac_assign_subject
CREATE OR REPLACE FUNCTION public.c77_rbac_assign_subject(
    p_external_id TEXT,
    p_role_name TEXT,
    p_scope_type TEXT,
    p_scope_id TEXT
) RETURNS VOID AS $$
DECLARE
    v_subject_id BIGINT;
    v_role_id BIGINT;
BEGIN
    INSERT INTO public.c77_rbac_subjects (external_id)
    VALUES (p_external_id)
    ON CONFLICT (external_id) DO NOTHING
    RETURNING subject_id INTO v_subject_id;

    IF v_subject_id IS NULL THEN
        SELECT subject_id INTO v_subject_id
        FROM public.c77_rbac_subjects
        WHERE external_id = p_external_id;
    END IF;

    INSERT INTO public.c77_rbac_roles (name)
    VALUES (p_role_name)
    ON CONFLICT (name) DO NOTHING
    RETURNING role_id INTO v_role_id;

    IF v_role_id IS NULL THEN
        SELECT role_id INTO v_role_id
        FROM public.c77_rbac_roles
        WHERE name = p_role_name;
    END IF;

    INSERT INTO public.c77_rbac_subject_roles (subject_id, role_id, scope_type, scope_id)
    VALUES (v_subject_id, v_role_id, p_scope_type, p_scope_id)
    ON CONFLICT (subject_id, role_id, scope_type, scope_id) DO NOTHING;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Function: c77_rbac_grant_feature
CREATE OR REPLACE FUNCTION public.c77_rbac_grant_feature(
    p_role_name TEXT,
    p_feature_name TEXT
) RETURNS VOID AS $$
DECLARE
    v_role_id BIGINT;
    v_feature_id BIGINT;
BEGIN
    INSERT INTO public.c77_rbac_roles (name)
    VALUES (p_role_name)
    ON CONFLICT (name) DO NOTHING
    RETURNING role_id INTO v_role_id;

    IF v_role_id IS NULL THEN
        SELECT role_id INTO v_role_id
        FROM public.c77_rbac_roles
        WHERE name = p_role_name;
    END IF;

    INSERT INTO public.c77_rbac_features (name)
    VALUES (p_feature_name)
    ON CONFLICT (name) DO NOTHING
    RETURNING feature_id INTO v_feature_id;

    IF v_feature_id IS NULL THEN
        SELECT feature_id INTO v_feature_id
        FROM public.c77_rbac_features
        WHERE name = p_feature_name;
    END IF;

    INSERT INTO public.c77_rbac_role_features (role_id, feature_id)
    VALUES (v_role_id, v_feature_id)
    ON CONFLICT (role_id, feature_id) DO NOTHING;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Function: c77_rbac_can_access
CREATE OR REPLACE FUNCTION public.c77_rbac_can_access(
    p_feature_name TEXT,
    p_external_id TEXT,
    p_scope_type TEXT,
    p_scope_id TEXT
) RETURNS BOOLEAN AS $$
BEGIN
    IF p_external_id IS NULL THEN
        RAISE EXCEPTION 'p_external_id must be provided';
    END IF;

    -- Admin bypass (global/all scope)
    IF EXISTS (
        SELECT 1
        FROM public.c77_rbac_subjects s
                 JOIN public.c77_rbac_subject_roles sr ON s.subject_id = sr.subject_id
                 JOIN public.c77_rbac_roles r ON sr.role_id = r.role_id
                 JOIN public.c77_rbac_role_features rf ON r.role_id = rf.role_id
                 JOIN public.c77_rbac_features f ON rf.feature_id = f.id
        WHERE s.external_id = p_external_id
          AND f.name = p_feature_name
          AND sr.scope_type = 'global'
          AND sr.scope_id = 'all'
    ) THEN
        RETURN TRUE;
    END IF;

    -- Regular access check
    RETURN EXISTS (
        SELECT 1
        FROM public.c77_rbac_subjects s
                 JOIN public.c77_rbac_subject_roles sr ON s.subject_id = sr.subject_id
                 JOIN public.c77_rbac_roles r ON sr.role_id = r.role_id
                 JOIN public.c77_rbac_role_features rf ON r.role_id = rf.role_id
                 JOIN public.c77_rbac_features f ON rf.feature_id = f.id
        WHERE s.external_id = p_external_id
          AND f.name = p_feature_name
          AND sr.scope_type = p_scope_type
          AND sr.scope_id = p_scope_id
    );
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Function: c77_rbac_apply_policy
CREATE OR REPLACE FUNCTION public.c77_rbac_apply_policy(
    p_table_name TEXT,
    p_feature_name TEXT,
    p_scope_type TEXT,
    p_scope_column TEXT
) RETURNS VOID AS $$
DECLARE
    v_schema_name TEXT;
    v_table_name TEXT;
BEGIN
    -- Split schema and table name
    IF p_table_name LIKE '%.%' THEN
        v_schema_name := split_part(p_table_name, '.', 1);
        v_table_name := split_part(p_table_name, '.', 2);
    ELSE
        v_schema_name := 'public';
        v_table_name := p_table_name;
    END IF;

    -- Drop existing policy
    EXECUTE format('DROP POLICY IF EXISTS c77_rbac_policy ON %I.%I', v_schema_name, v_table_name);

    -- Create policy with fully qualified column
    EXECUTE format(
            'CREATE POLICY c77_rbac_policy ON %I.%I FOR ALL TO PUBLIC USING (
                public.c77_rbac_can_access(%L, current_setting(''c77_rbac.external_id'', true), %L, %I.%I.%I)
            )',
            v_schema_name, v_table_name, p_feature_name, p_scope_type, v_schema_name, v_table_name, p_scope_column
            );

    -- Enable and force RLS
    EXECUTE format('ALTER TABLE %I.%I ENABLE ROW LEVEL SECURITY', v_schema_name, v_table_name);
    EXECUTE format('ALTER TABLE %I.%I FORCE ROW LEVEL SECURITY', v_schema_name, v_table_name);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Grant permissions
GRANT USAGE ON SCHEMA public TO PUBLIC;
GRANT SELECT, INSERT, UPDATE, DELETE ON public.c77_rbac_subjects, public.c77_rbac_roles, public.c77_rbac_features,
    public.c77_rbac_subject_roles, public.c77_rbac_role_features TO PUBLIC;
GRANT EXECUTE ON FUNCTION public.c77_rbac_assign_subject(TEXT, TEXT, TEXT, TEXT),
    public.c77_rbac_grant_feature(TEXT, TEXT),
    public.c77_rbac_can_access(TEXT, TEXT, TEXT, TEXT),
    public.c77_rbac_apply_policy(TEXT, TEXT, TEXT, TEXT) TO PUBLIC;

-- Set default privileges for future objects
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO PUBLIC;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT EXECUTE ON FUNCTIONS TO PUBLIC;