-- 平台治理：租户 / 审批 / 审计（字段以 platform_store 实际写入为准）
CREATE TABLE IF NOT EXISTS tenants (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    code TEXT,
    status TEXT DEFAULT 'active',
    owner_user_id TEXT,
    quota TEXT,
    retention_policy_id TEXT,
    create_time TEXT
);

CREATE TABLE IF NOT EXISTS approval_templates (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    steps TEXT,
    create_time TEXT
);

CREATE TABLE IF NOT EXISTS approval_instances (
    id TEXT PRIMARY KEY,
    template_id TEXT,
    resource_type TEXT,
    resource_id TEXT,
    applicant_id TEXT,
    status TEXT DEFAULT 'pending',
    current_step INTEGER DEFAULT 0,
    create_time TEXT
);

CREATE TABLE IF NOT EXISTS approval_steps (
    id TEXT PRIMARY KEY,
    instance_id TEXT,
    step_index INTEGER,
    approver_id TEXT,
    status TEXT DEFAULT 'pending',
    comment TEXT,
    time TEXT
);

CREATE TABLE IF NOT EXISTS audit_logs (
    id TEXT PRIMARY KEY,
    tenant_id TEXT,
    project_id TEXT,
    actor_id TEXT,
    action TEXT,
    target_type TEXT,
    target_id TEXT,
    detail TEXT,
    client_ip TEXT,
    time TEXT
);

-- 幂等升级 audit_logs 表：新增字段（已存在则跳过）
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS trace_id TEXT;
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS request_method TEXT;
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS request_path TEXT;
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS status_code INTEGER;
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS duration_ms REAL;
ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS extra JSONB;

-- 索引（已存在则跳过）
CREATE INDEX IF NOT EXISTS idx_audit_trace ON audit_logs(trace_id);
CREATE INDEX IF NOT EXISTS idx_audit_actor_time ON audit_logs(actor_id, time);
CREATE INDEX IF NOT EXISTS idx_audit_target ON audit_logs(target_type, target_id);

CREATE TABLE IF NOT EXISTS retention_policies (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    scope TEXT,
    rule TEXT,
    status TEXT DEFAULT 'active',
    create_time TEXT,
    create_by TEXT,
    updated_at TEXT
);
