-- 007-ai-agent-profile-policy.sql
-- Page AI agent profile policy: SQLite 是 profile 授权与归属真相层。

CREATE TABLE IF NOT EXISTS ai_agent_profiles (
  id TEXT PRIMARY KEY,
  agent_id TEXT NOT NULL,
  profile_kind TEXT NOT NULL,
  owner_user_id TEXT NOT NULL DEFAULT '',
  base_profile_name TEXT NOT NULL,
  isolated_profile_name TEXT NOT NULL,
  display_name TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'active',
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  revision INTEGER NOT NULL DEFAULT 1,
  UNIQUE(agent_id, profile_kind, owner_user_id, base_profile_name)
);

CREATE INDEX IF NOT EXISTS idx_ai_agent_profiles_agent
  ON ai_agent_profiles(agent_id, status);

CREATE INDEX IF NOT EXISTS idx_ai_agent_profiles_owner
  ON ai_agent_profiles(owner_user_id, status);

CREATE TABLE IF NOT EXISTS ai_agent_profile_grants (
  id TEXT PRIMARY KEY,
  profile_id TEXT NOT NULL REFERENCES ai_agent_profiles(id) ON DELETE CASCADE,
  user_id TEXT NOT NULL DEFAULT '',
  role TEXT NOT NULL,
  can_run INTEGER NOT NULL DEFAULT 1,
  can_manage_skills INTEGER NOT NULL DEFAULT 0,
  can_manage_config INTEGER NOT NULL DEFAULT 0,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  revision INTEGER NOT NULL DEFAULT 1,
  UNIQUE(profile_id, user_id, role)
);

CREATE INDEX IF NOT EXISTS idx_ai_agent_profile_grants_profile
  ON ai_agent_profile_grants(profile_id);

CREATE INDEX IF NOT EXISTS idx_ai_agent_profile_grants_user
  ON ai_agent_profile_grants(user_id);
