-- ============================================================
-- post-boot — runs after all migrations have been applied.
-- Grants permissions to authenticator and supabase_admin,
-- then seeds initial admin user (telegram_id 298181113).
-- ============================================================

-- -----------------------------------------------------------
-- supabase_admin — role for Supabase Studio / pg-meta
-- Uses explicit grants rather than SUPERUSER + hardcoded pass.
-- -----------------------------------------------------------
DO $$ BEGIN
    IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'supabase_admin') THEN
        CREATE ROLE supabase_admin WITH LOGIN;
    END IF;
END $$;

GRANT USAGE ON SCHEMA public TO supabase_admin;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO supabase_admin;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO supabase_admin;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
    GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO supabase_admin;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
    GRANT USAGE, SELECT ON SEQUENCES TO supabase_admin;

-- -----------------------------------------------------------
-- authenticator — writes to user-facing tables (PostgREST)
-- -----------------------------------------------------------
GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA public TO authenticator;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO authenticator;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
    GRANT SELECT, INSERT, UPDATE ON TABLES TO authenticator;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
    GRANT USAGE, SELECT ON SEQUENCES TO authenticator;

-- -----------------------------------------------------------
-- Seed: initial admin user
-- -----------------------------------------------------------
INSERT INTO users (telegram_id, username, first_name, is_admin, is_active)
VALUES (298181113, NULL, 'Admin', true, true)
ON CONFLICT (telegram_id) DO NOTHING;
