-- ============================================================
-- 表15：access_grants（访问权限表）
-- 用途：动态权限接口，由冰朔手动生成
-- 冰朔权限控制三层：对国家系统逻辑完全透明 → 国家系统逻辑审核 → 光湖团队审核 → 冰朔本人
-- ============================================================

CREATE TABLE IF NOT EXISTS access_grants (
  grant_id          VARCHAR(64)   PRIMARY KEY,
  grantee_type      VARCHAR(16)   NOT NULL
                    CHECK (grantee_type IN ('persona', 'system', 'national', 'user', 'emergency')),
  grantee_id        VARCHAR(64)   NOT NULL,
  resource_type     VARCHAR(32)   NOT NULL,
  resource_id       VARCHAR(64),
  permissions       TEXT          NOT NULL,        -- JSON array of permissions
  grant_conditions  TEXT,                          -- JSON object of conditions
  valid_from        TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP,
  valid_until       TIMESTAMP,
  issued_by         VARCHAR(64)   NOT NULL,
  status            VARCHAR(16)   NOT NULL DEFAULT 'active'
                    CHECK (status IN ('active', 'revoked', 'expired')),
  created_at        TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_ag_grantee ON access_grants(grantee_type, grantee_id);
CREATE INDEX IF NOT EXISTS idx_ag_resource ON access_grants(resource_type, resource_id);
CREATE INDEX IF NOT EXISTS idx_ag_status ON access_grants(status);
