-- FFAI Agent 模块完整 schema —— Phase 1 PR0.5/PR2/PR3.5/PR3.6/PR4.5/PR4c/PR9/PR8/PR10.5 合并迁移
-- 详见 docs/modules/agent/01-prd-phase1.md §10.5 实现快照


-- CreateEnum
CREATE TYPE "platform_ai"."AgentSurface" AS ENUM ('WEB', 'CLI', 'TEAMS', 'DESKTOP', 'IOS', 'ANDROID');

-- CreateEnum
CREATE TYPE "platform_ai"."AgentSessionStatus" AS ENUM ('ACTIVE', 'CLOSED', 'ARCHIVED');

-- CreateEnum
CREATE TYPE "platform_ai"."AgentMessageType" AS ENUM ('USER_PROMPT', 'ASSISTANT_TEXT', 'TOOL_USE', 'TOOL_RESULT', 'A2UI_COMPONENT', 'TURN_DONE');

-- CreateEnum
CREATE TYPE "platform_ai"."ModelRoutingScope" AS ENUM ('ORGANIZATION', 'USER', 'PROJECT');

-- CreateEnum
CREATE TYPE "platform_ai"."ModelRoutingMatchSource" AS ENUM ('RULE', 'LLM_ROUTED', 'SCOPE_OVERRIDE', 'DEFAULT');

-- CreateEnum
CREATE TYPE "platform_ai"."AgentTrajectoryEventType" AS ENUM ('TURN_STARTED', 'ROUTING_DECIDED', 'PROVIDER_INVOKED', 'MESSAGE_APPENDED', 'TURN_DONE', 'TOOL_CALL', 'TOOL_RESULT');

-- CreateEnum
CREATE TYPE "platform_ai"."AgentQuotaScope" AS ENUM ('ORGANIZATION', 'USER');

-- CreateEnum
CREATE TYPE "platform_ai"."AgentPlanMode" AS ENUM ('OFF', 'REQUIRED');

-- CreateEnum
CREATE TYPE "platform_ai"."AgentPermissionMode" AS ENUM ('DEFAULT', 'BYPASS', 'READ_ONLY', 'ASK_EVERY_TIME');

-- CreateEnum
CREATE TYPE "platform_ai"."AgentArtifactType" AS ENUM ('TABLE', 'CHART', 'FILE', 'LINK', 'TEXT');

-- CreateEnum
CREATE TYPE "platform_ai"."AgentTaskStatus" AS ENUM ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED', 'FAILED');

-- CreateEnum
CREATE TYPE "platform_ai"."StorageBindingScope" AS ENUM ('ORGANIZATION', 'USER', 'PROJECT');

-- CreateEnum
CREATE TYPE "platform_ai"."StorageBackendKind" AS ENUM ('LOCAL', 'ONEDRIVE', 'S3', 'GOOGLE_DRIVE');

-- AlterTable
ALTER TABLE "platform_ai"."ai_assistant_tickets" ALTER COLUMN "assignedAt" SET DATA TYPE TIMESTAMPTZ(3),
ALTER COLUMN "resolvedAt" SET DATA TYPE TIMESTAMPTZ(3),
ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3),
ALTER COLUMN "updatedAt" SET DATA TYPE TIMESTAMPTZ(3);

-- AlterTable
ALTER TABLE "platform_ai"."ai_configurations" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3),
ALTER COLUMN "updatedAt" SET DATA TYPE TIMESTAMPTZ(3);

-- AlterTable
ALTER TABLE "platform_ai"."ai_conversations" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3),
ALTER COLUMN "updatedAt" SET DATA TYPE TIMESTAMPTZ(3);

-- AlterTable
ALTER TABLE "platform_ai"."ai_knowledge_fixes" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3),
ALTER COLUMN "reviewedAt" SET DATA TYPE TIMESTAMPTZ(3);

-- AlterTable
ALTER TABLE "platform_ai"."ai_message_feedbacks" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);

-- AlterTable
ALTER TABLE "platform_ai"."ai_messages" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);

-- AlterTable
ALTER TABLE "platform_ai"."ai_prompt_templates" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3),
ALTER COLUMN "updatedAt" SET DATA TYPE TIMESTAMPTZ(3);

-- AlterTable
ALTER TABLE "platform_ai"."ai_usage_stats" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3),
ALTER COLUMN "updatedAt" SET DATA TYPE TIMESTAMPTZ(3);

-- CreateTable
CREATE TABLE "platform_ai"."agent_sessions" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "createdById" UUID NOT NULL,
    "title" VARCHAR(255),
    "surface" "platform_ai"."AgentSurface" NOT NULL DEFAULT 'WEB',
    "status" "platform_ai"."AgentSessionStatus" NOT NULL DEFAULT 'ACTIVE',
    "projectId" UUID,
    "planMode" "platform_ai"."AgentPlanMode" NOT NULL DEFAULT 'OFF',
    "permissionMode" "platform_ai"."AgentPermissionMode" NOT NULL DEFAULT 'DEFAULT',
    "closedAt" TIMESTAMPTZ(3),
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMPTZ(3) NOT NULL,

    CONSTRAINT "agent_sessions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."agent_messages" (
    "id" UUID NOT NULL,
    "sessionId" UUID NOT NULL,
    "turnId" UUID NOT NULL,
    "type" "platform_ai"."AgentMessageType" NOT NULL,
    "content" TEXT,
    "payload" JSONB,
    "model" VARCHAR(120),
    "sequence" INTEGER NOT NULL,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "agent_messages_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."model_routing_rules" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "scope" "platform_ai"."ModelRoutingScope" NOT NULL DEFAULT 'ORGANIZATION',
    "scopeRefId" UUID NOT NULL,
    "name" VARCHAR(255) NOT NULL,
    "priority" INTEGER NOT NULL DEFAULT 500,
    "enabled" BOOLEAN NOT NULL DEFAULT true,
    "pattern" JSONB NOT NULL,
    "primary" JSONB NOT NULL,
    "fallbacks" JSONB NOT NULL DEFAULT '[]',
    "reasoning" TEXT,
    "createdById" UUID NOT NULL,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMPTZ(3) NOT NULL,

    CONSTRAINT "model_routing_rules_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."model_routing_decisions" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "sessionId" UUID,
    "turnId" UUID,
    "request" JSONB NOT NULL,
    "decision" JSONB NOT NULL,
    "matchSource" "platform_ai"."ModelRoutingMatchSource" NOT NULL,
    "matchedRuleId" UUID,
    "primaryProvider" VARCHAR(60) NOT NULL,
    "primaryModel" VARCHAR(120) NOT NULL,
    "estimatedCostUsd" DOUBLE PRECISION,
    "actualCostUsd" DOUBLE PRECISION,
    "actualLatencyMs" INTEGER,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "model_routing_decisions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."agent_trajectory_events" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "sessionId" UUID NOT NULL,
    "turnId" UUID,
    "eventType" "platform_ai"."AgentTrajectoryEventType" NOT NULL,
    "payload" JSONB NOT NULL,
    "sequenceInSession" INTEGER NOT NULL,
    "prevEventHash" CHAR(64),
    "eventHash" CHAR(64) NOT NULL,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "agent_trajectory_events_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."agent_quotas" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "scope" "platform_ai"."AgentQuotaScope" NOT NULL,
    "scopeRefId" UUID NOT NULL,
    "monthlyTokens" INTEGER NOT NULL DEFAULT 1000000,
    "monthlyCostUsd" DOUBLE PRECISION NOT NULL DEFAULT 50.0,
    "softLimitRatio" DOUBLE PRECISION NOT NULL DEFAULT 0.8,
    "enabled" BOOLEAN NOT NULL DEFAULT true,
    "createdById" UUID NOT NULL,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMPTZ(3) NOT NULL,

    CONSTRAINT "agent_quotas_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."agent_quota_usage" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "scope" "platform_ai"."AgentQuotaScope" NOT NULL,
    "scopeRefId" UUID NOT NULL,
    "periodStart" DATE NOT NULL,
    "tokensUsed" INTEGER NOT NULL DEFAULT 0,
    "costUsdUsed" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "updatedAt" TIMESTAMPTZ(3) NOT NULL,

    CONSTRAINT "agent_quota_usage_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."organization_agent_settings" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "defaultPlanMode" "platform_ai"."AgentPlanMode" NOT NULL DEFAULT 'OFF',
    "defaultPermissionMode" "platform_ai"."AgentPermissionMode" NOT NULL DEFAULT 'DEFAULT',
    "disabledCapabilities" TEXT[] DEFAULT ARRAY[]::TEXT[],
    "allowedCliTools" TEXT[] DEFAULT ARRAY[]::TEXT[],
    "allowedPermissionModes" TEXT[] DEFAULT ARRAY[]::TEXT[],
    "createdById" UUID NOT NULL,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMPTZ(3) NOT NULL,

    CONSTRAINT "organization_agent_settings_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."agent_artifacts" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "sessionId" UUID NOT NULL,
    "turnId" UUID,
    "createdById" UUID NOT NULL,
    "type" "platform_ai"."AgentArtifactType" NOT NULL,
    "title" VARCHAR(255) NOT NULL,
    "data" JSONB NOT NULL,
    "previewUrl" VARCHAR(2048),
    "mimeType" VARCHAR(120),
    "sizeBytes" INTEGER,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMPTZ(3) NOT NULL,

    CONSTRAINT "agent_artifacts_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."agent_task_tracker" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "sessionId" UUID NOT NULL,
    "parentTaskId" UUID,
    "title" VARCHAR(255) NOT NULL,
    "description" TEXT,
    "status" "platform_ai"."AgentTaskStatus" NOT NULL DEFAULT 'PENDING',
    "progress" INTEGER NOT NULL DEFAULT 0,
    "metadata" JSONB,
    "createdById" UUID NOT NULL,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMPTZ(3) NOT NULL,

    CONSTRAINT "agent_task_tracker_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."agent_scratchpad" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "sessionId" UUID NOT NULL,
    "key" VARCHAR(255) NOT NULL,
    "value" JSONB NOT NULL,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMPTZ(3) NOT NULL,

    CONSTRAINT "agent_scratchpad_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."storage_bindings" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "scope" "platform_ai"."StorageBindingScope" NOT NULL,
    "scopeRefId" UUID NOT NULL,
    "kind" "platform_ai"."StorageBackendKind" NOT NULL,
    "displayName" VARCHAR(255) NOT NULL,
    "config" JSONB NOT NULL,
    "encryptedSecret" TEXT,
    "keyId" VARCHAR(255),
    "enabled" BOOLEAN NOT NULL DEFAULT true,
    "createdById" UUID NOT NULL,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMPTZ(3) NOT NULL,

    CONSTRAINT "storage_bindings_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "platform_ai"."storage_files" (
    "id" UUID NOT NULL,
    "bindingId" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "path" VARCHAR(2048) NOT NULL,
    "externalId" VARCHAR(255),
    "sizeBytes" INTEGER NOT NULL,
    "mimeType" VARCHAR(120),
    "sha256" CHAR(64) NOT NULL,
    "encrypted" BOOLEAN NOT NULL DEFAULT false,
    "uploadedById" UUID NOT NULL,
    "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "storage_files_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "agent_sessions_organizationId_createdAt_idx" ON "platform_ai"."agent_sessions"("organizationId", "createdAt" DESC);

-- CreateIndex
CREATE INDEX "agent_sessions_createdById_createdAt_idx" ON "platform_ai"."agent_sessions"("createdById", "createdAt" DESC);

-- CreateIndex
CREATE INDEX "agent_sessions_status_idx" ON "platform_ai"."agent_sessions"("status");

-- CreateIndex
CREATE INDEX "agent_messages_sessionId_sequence_idx" ON "platform_ai"."agent_messages"("sessionId", "sequence");

-- CreateIndex
CREATE INDEX "agent_messages_sessionId_createdAt_idx" ON "platform_ai"."agent_messages"("sessionId", "createdAt");

-- CreateIndex
CREATE INDEX "agent_messages_turnId_idx" ON "platform_ai"."agent_messages"("turnId");

-- CreateIndex
CREATE INDEX "model_routing_rules_organizationId_scope_enabled_priority_idx" ON "platform_ai"."model_routing_rules"("organizationId", "scope", "enabled", "priority");

-- CreateIndex
CREATE INDEX "model_routing_rules_scopeRefId_scope_idx" ON "platform_ai"."model_routing_rules"("scopeRefId", "scope");

-- CreateIndex
CREATE INDEX "model_routing_decisions_organizationId_createdAt_idx" ON "platform_ai"."model_routing_decisions"("organizationId", "createdAt" DESC);

-- CreateIndex
CREATE INDEX "model_routing_decisions_sessionId_createdAt_idx" ON "platform_ai"."model_routing_decisions"("sessionId", "createdAt");

-- CreateIndex
CREATE INDEX "model_routing_decisions_matchSource_createdAt_idx" ON "platform_ai"."model_routing_decisions"("matchSource", "createdAt");

-- CreateIndex
CREATE INDEX "model_routing_decisions_primaryProvider_primaryModel_create_idx" ON "platform_ai"."model_routing_decisions"("primaryProvider", "primaryModel", "createdAt");

-- CreateIndex
CREATE INDEX "agent_trajectory_events_organizationId_createdAt_idx" ON "platform_ai"."agent_trajectory_events"("organizationId", "createdAt" DESC);

-- CreateIndex
CREATE INDEX "agent_trajectory_events_sessionId_sequenceInSession_idx" ON "platform_ai"."agent_trajectory_events"("sessionId", "sequenceInSession");

-- CreateIndex
CREATE INDEX "agent_trajectory_events_turnId_idx" ON "platform_ai"."agent_trajectory_events"("turnId");

-- CreateIndex
CREATE INDEX "agent_trajectory_events_eventType_createdAt_idx" ON "platform_ai"."agent_trajectory_events"("eventType", "createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "agent_trajectory_events_sessionId_sequenceInSession_key" ON "platform_ai"."agent_trajectory_events"("sessionId", "sequenceInSession");

-- CreateIndex
CREATE INDEX "agent_quotas_organizationId_idx" ON "platform_ai"."agent_quotas"("organizationId");

-- CreateIndex
CREATE UNIQUE INDEX "agent_quotas_scope_scopeRefId_key" ON "platform_ai"."agent_quotas"("scope", "scopeRefId");

-- CreateIndex
CREATE INDEX "agent_quota_usage_organizationId_periodStart_idx" ON "platform_ai"."agent_quota_usage"("organizationId", "periodStart");

-- CreateIndex
CREATE UNIQUE INDEX "agent_quota_usage_scope_scopeRefId_periodStart_key" ON "platform_ai"."agent_quota_usage"("scope", "scopeRefId", "periodStart");

-- CreateIndex
CREATE UNIQUE INDEX "organization_agent_settings_organizationId_key" ON "platform_ai"."organization_agent_settings"("organizationId");

-- CreateIndex
CREATE INDEX "organization_agent_settings_organizationId_idx" ON "platform_ai"."organization_agent_settings"("organizationId");

-- CreateIndex
CREATE INDEX "agent_artifacts_sessionId_createdAt_idx" ON "platform_ai"."agent_artifacts"("sessionId", "createdAt" DESC);

-- CreateIndex
CREATE INDEX "agent_artifacts_organizationId_type_createdAt_idx" ON "platform_ai"."agent_artifacts"("organizationId", "type", "createdAt" DESC);

-- CreateIndex
CREATE INDEX "agent_task_tracker_sessionId_status_idx" ON "platform_ai"."agent_task_tracker"("sessionId", "status");

-- CreateIndex
CREATE INDEX "agent_task_tracker_organizationId_status_createdAt_idx" ON "platform_ai"."agent_task_tracker"("organizationId", "status", "createdAt" DESC);

-- CreateIndex
CREATE INDEX "agent_task_tracker_parentTaskId_idx" ON "platform_ai"."agent_task_tracker"("parentTaskId");

-- CreateIndex
CREATE INDEX "agent_scratchpad_organizationId_sessionId_idx" ON "platform_ai"."agent_scratchpad"("organizationId", "sessionId");

-- CreateIndex
CREATE UNIQUE INDEX "agent_scratchpad_sessionId_key_key" ON "platform_ai"."agent_scratchpad"("sessionId", "key");

-- CreateIndex
CREATE INDEX "storage_bindings_organizationId_scope_scopeRefId_idx" ON "platform_ai"."storage_bindings"("organizationId", "scope", "scopeRefId");

-- CreateIndex
CREATE INDEX "storage_bindings_kind_enabled_idx" ON "platform_ai"."storage_bindings"("kind", "enabled");

-- CreateIndex
CREATE INDEX "storage_files_organizationId_createdAt_idx" ON "platform_ai"."storage_files"("organizationId", "createdAt" DESC);

-- CreateIndex
CREATE INDEX "storage_files_bindingId_path_idx" ON "platform_ai"."storage_files"("bindingId", "path");

-- CreateIndex
CREATE INDEX "storage_files_sha256_idx" ON "platform_ai"."storage_files"("sha256");

-- AddForeignKey
ALTER TABLE "platform_ai"."agent_messages" ADD CONSTRAINT "agent_messages_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "platform_ai"."agent_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "platform_ai"."storage_files" ADD CONSTRAINT "storage_files_bindingId_fkey" FOREIGN KEY ("bindingId") REFERENCES "platform_ai"."storage_bindings"("id") ON DELETE CASCADE ON UPDATE CASCADE;

