-- ============================================================
-- 🧩 INIT SCRIPT: CREATE LIMITED APP USER FOR LTI API
-- ============================================================

-- Buat user aplikasi jika belum ada
DO
$$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'app_lti_user') THEN
        CREATE ROLE app_lti_user WITH LOGIN PASSWORD 'AppLti@Secure2025!' NOINHERIT NOCREATEROLE NOCREATEDB NOSUPERUSER;
        RAISE NOTICE '✅ Role app_lti_user created successfully.';
    ELSE
        RAISE NOTICE 'ℹ️ Role app_lti_user already exists.';
    END IF;
END
$$;

-- Buat database jika belum ada
DO
$$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_database WHERE datname = 'db_lti_erp') THEN
        CREATE DATABASE db_lti_erp OWNER app_lti_user;
        RAISE NOTICE '✅ Database db_lti_erp created and owned by app_lti_user.';
    ELSE
        RAISE NOTICE 'ℹ️ Database db_lti_erp already exists.';
    END IF;
END
$$;

\connect db_lti_erp

-- Beri hak CRUD untuk app_lti_user
GRANT CONNECT ON DATABASE db_lti_erp TO app_lti_user;
GRANT USAGE ON SCHEMA public TO app_lti_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_lti_user;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app_lti_user;

-- Set default privileges agar tabel baru juga bisa diakses
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_lti_user;

ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT USAGE, SELECT ON SEQUENCES TO app_lti_user;

-- Tampilkan hasil
\du app_lti_user
