-- SEO Operations Center
--
-- Adds the persistence layer for the SEO module:
--   * Redirect: runtime + management columns (enabled, priority, preserveQuery,
--     source_kind, hits, lastHitAt, createdById).
--   * SeoAuditRun: one row per audit execution (score + issue-count snapshot).
--   * SeoIssue: detected SEO problems, status carried across runs via issueKey.
--   * Redirect404Hit: aggregated 404 traffic observed by the middleware.
--   * RedirectSuggestion: confidence-scored 404 recovery / chain suggestions.
--
-- Safe to apply to a populated database:
--   * Every new Redirect column is nullable or has a default — no backfill.
--   * New tables/enums are additive; no existing column is dropped or retyped.

-- ---------------------------------------------------------------------------
-- Enums
-- ---------------------------------------------------------------------------
CREATE TYPE "SeoAuditStatus" AS ENUM ('RUNNING', 'COMPLETED', 'FAILED');
CREATE TYPE "SeoIssueSeverity" AS ENUM ('critical', 'warning', 'info');
CREATE TYPE "SeoIssueStatus" AS ENUM ('open', 'ignored', 'resolved', 'recurring');
CREATE TYPE "SeoIssueCategory" AS ENUM (
  'content', 'technical', 'redirects', 'media',
  'performance', 'schema', 'social', 'indexing'
);

-- ---------------------------------------------------------------------------
-- actuate_redirects new columns
-- ---------------------------------------------------------------------------
ALTER TABLE "actuate_redirects"
  ADD COLUMN "enabled"       BOOLEAN NOT NULL DEFAULT true,
  ADD COLUMN "priority"      INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN "preserveQuery" BOOLEAN NOT NULL DEFAULT false,
  ADD COLUMN "source_kind"   TEXT NOT NULL DEFAULT 'manual',
  ADD COLUMN "hits"          INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN "lastHitAt"     TIMESTAMP(3),
  ADD COLUMN "createdById"   TEXT;

CREATE INDEX "actuate_redirects_enabled_idx" ON "actuate_redirects" ("enabled");
CREATE INDEX "actuate_redirects_lastHitAt_idx" ON "actuate_redirects" ("lastHitAt");

-- ---------------------------------------------------------------------------
-- actuate_seo_audit_runs
-- ---------------------------------------------------------------------------
CREATE TABLE "actuate_seo_audit_runs" (
  "id"              TEXT NOT NULL,
  "status"          "SeoAuditStatus" NOT NULL DEFAULT 'RUNNING',
  "scope"           TEXT NOT NULL DEFAULT 'full',
  "startedById"     TEXT,
  "startedAt"       TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "finishedAt"      TIMESTAMP(3),
  "siteScoreBefore" INTEGER,
  "siteScoreAfter"  INTEGER,
  "pagesScanned"    INTEGER NOT NULL DEFAULT 0,
  "issuesFound"     INTEGER NOT NULL DEFAULT 0,
  "criticalCount"   INTEGER NOT NULL DEFAULT 0,
  "warningCount"    INTEGER NOT NULL DEFAULT 0,
  "infoCount"       INTEGER NOT NULL DEFAULT 0,
  "errorMessage"    TEXT,
  "metadata"        JSONB,
  CONSTRAINT "actuate_seo_audit_runs_pkey" PRIMARY KEY ("id")
);

CREATE INDEX "actuate_seo_audit_runs_status_idx" ON "actuate_seo_audit_runs" ("status");
CREATE INDEX "actuate_seo_audit_runs_startedAt_idx" ON "actuate_seo_audit_runs" ("startedAt");

-- ---------------------------------------------------------------------------
-- actuate_seo_issues
-- ---------------------------------------------------------------------------
CREATE TABLE "actuate_seo_issues" (
  "id"               TEXT NOT NULL,
  "auditRunId"       TEXT,
  "issueKey"         TEXT NOT NULL,
  "entityType"       TEXT,
  "entityId"         TEXT,
  "entityTitle"      TEXT,
  "url"              TEXT,
  "severity"         "SeoIssueSeverity" NOT NULL,
  "category"         "SeoIssueCategory" NOT NULL,
  "type"             TEXT NOT NULL,
  "title"            TEXT NOT NULL,
  "description"      TEXT,
  "impact"           TEXT,
  "recommendation"   TEXT,
  "status"           "SeoIssueStatus" NOT NULL DEFAULT 'open',
  "fixable"          BOOLEAN NOT NULL DEFAULT false,
  "fixActionType"    TEXT,
  "relatedEntityIds" JSONB,
  "source"           TEXT NOT NULL DEFAULT 'audit',
  "firstDetectedAt"  TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "lastDetectedAt"   TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "resolvedAt"       TIMESTAMP(3),
  "resolvedById"     TEXT,
  "metadata"         JSONB,
  CONSTRAINT "actuate_seo_issues_pkey" PRIMARY KEY ("id")
);

CREATE INDEX "actuate_seo_issues_auditRunId_idx" ON "actuate_seo_issues" ("auditRunId");
CREATE INDEX "actuate_seo_issues_status_idx" ON "actuate_seo_issues" ("status");
CREATE INDEX "actuate_seo_issues_severity_idx" ON "actuate_seo_issues" ("severity");
CREATE INDEX "actuate_seo_issues_category_idx" ON "actuate_seo_issues" ("category");
CREATE INDEX "actuate_seo_issues_issueKey_idx" ON "actuate_seo_issues" ("issueKey");

ALTER TABLE "actuate_seo_issues"
  ADD CONSTRAINT "actuate_seo_issues_auditRunId_fkey"
  FOREIGN KEY ("auditRunId") REFERENCES "actuate_seo_audit_runs"("id")
  ON DELETE SET NULL ON UPDATE CASCADE;

-- ---------------------------------------------------------------------------
-- actuate_redirect_404_hits
-- ---------------------------------------------------------------------------
CREATE TABLE "actuate_redirect_404_hits" (
  "id"          TEXT NOT NULL,
  "path"        TEXT NOT NULL,
  "hits"        INTEGER NOT NULL DEFAULT 1,
  "referrer"    TEXT,
  "resolvedAt"  TIMESTAMP(3),
  "firstSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "lastSeenAt"  TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT "actuate_redirect_404_hits_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "actuate_redirect_404_hits_path_key" ON "actuate_redirect_404_hits" ("path");
CREATE INDEX "actuate_redirect_404_hits_lastSeenAt_idx" ON "actuate_redirect_404_hits" ("lastSeenAt");

-- ---------------------------------------------------------------------------
-- actuate_redirect_suggestions
-- ---------------------------------------------------------------------------
CREATE TABLE "actuate_redirect_suggestions" (
  "id"         TEXT NOT NULL,
  "fromPath"   TEXT NOT NULL,
  "toPath"     TEXT NOT NULL,
  "confidence" INTEGER NOT NULL DEFAULT 0,
  "reason"     TEXT,
  "status"     TEXT NOT NULL DEFAULT 'open',
  "source"     TEXT NOT NULL DEFAULT 'ai-404-recovery',
  "metadata"   JSONB,
  "createdAt"  TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt"  TIMESTAMP(3) NOT NULL,
  CONSTRAINT "actuate_redirect_suggestions_pkey" PRIMARY KEY ("id")
);

CREATE INDEX "actuate_redirect_suggestions_status_idx" ON "actuate_redirect_suggestions" ("status");
CREATE INDEX "actuate_redirect_suggestions_fromPath_idx" ON "actuate_redirect_suggestions" ("fromPath");
