-- Staff roles and fine-grained permissions on users

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'role'
  ) THEN
    ALTER TABLE users ADD COLUMN role VARCHAR(32) NOT NULL DEFAULT 'curator';
    ALTER TABLE users ADD COLUMN permissions TEXT[] NOT NULL DEFAULT '{}';
    ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;

    -- Existing accounts were full curators; promote to admin so nothing breaks
    UPDATE users
    SET role = 'admin',
        permissions = ARRAY[
          'images',
          'checkup',
          'curator_notes',
          'translations',
          'influences',
          'tours',
          'users'
        ]::text[];
  END IF;
END $$;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'users_role_check'
  ) THEN
    ALTER TABLE users ADD CONSTRAINT users_role_check CHECK (role IN ('admin', 'curator'));
  END IF;
END $$;
