-- Migration 003: Screen-User-Berechtigungssystem
-- Fügt die Rolle 'screen_user' und die M:N Tabelle user_screen_permissions hinzu.

-- Neue Spalte 'role' in users (DEFAULT 'screen_user' für zukünftige Nutzer).
ALTER TABLE users ADD COLUMN IF NOT EXISTS role TEXT DEFAULT 'screen_user';

-- Bestehende Admins auf 'admin' setzen (alle User im Standard-Tenant morz).
UPDATE users SET role = 'admin'
WHERE tenant_id = (SELECT id FROM tenants WHERE slug = 'morz')
  AND role IS DISTINCT FROM 'admin';

-- M:N-Tabelle: welche User dürfen welche Screens verwalten.
CREATE TABLE IF NOT EXISTS user_screen_permissions (
  id         UUID    PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id    TEXT    NOT NULL REFERENCES users(id)   ON DELETE CASCADE,
  screen_id  TEXT    NOT NULL REFERENCES screens(id) ON DELETE CASCADE,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(user_id, screen_id)
);

CREATE INDEX IF NOT EXISTS idx_user_screen_perms_user   ON user_screen_permissions(user_id);
CREATE INDEX IF NOT EXISTS idx_user_screen_perms_screen ON user_screen_permissions(screen_id);
