-- AlterTable
ALTER TABLE "Dealer" ADD COLUMN "gscVerificationToken" TEXT;
ALTER TABLE "Dealer" ADD COLUMN "gscPropertyRegisteredAt" TIMESTAMP(3);
ALTER TABLE "Dealer" ADD COLUMN "gscLastInspectedAt" TIMESTAMP(3);
ALTER TABLE "Dealer" ADD COLUMN "gscLastIndexStatus" TEXT;
ALTER TABLE "Dealer" ADD COLUMN "gscLastSubmittedAt" TIMESTAMP(3);
ALTER TABLE "Dealer" ADD COLUMN "gscPreflightHealthyAt" TIMESTAMP(3);
ALTER TABLE "Dealer" ADD COLUMN "gscPreflightError" TEXT;

-- CreateTable
CREATE TABLE "GscJob" (
    "id" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "dealerId" TEXT NOT NULL,
    "payload" JSONB NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'pending',
    "priority" INTEGER NOT NULL DEFAULT 100,
    "attempts" INTEGER NOT NULL DEFAULT 0,
    "maxAttempts" INTEGER NOT NULL DEFAULT 5,
    "lastError" TEXT,
    "runAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "startedAt" TIMESTAMP(3),
    "completedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "GscQuotaUsage" (
    "date" DATE NOT NULL,
    "indexingApiCalls" INTEGER NOT NULL DEFAULT 0,

    CONSTRAINT "GscQuotaUsage_pkey" PRIMARY KEY ("date")
);

-- CreateIndex
-- Worker claim query: WHERE status='pending' AND runAt<=NOW() ORDER BY priority ASC, runAt ASC.
-- (status, priority, runAt) lets the planner satisfy the equality + ORDER BY priority without
-- a sort step; runAt range predicate is applied last.
CREATE INDEX "GscJob_status_priority_runAt_idx" ON "GscJob"("status", "priority", "runAt");

-- CreateIndex
CREATE INDEX "GscJob_dealerId_idx" ON "GscJob"("dealerId");

-- CreateIndex
CREATE INDEX "GscJob_type_status_idx" ON "GscJob"("type", "status");

-- AddForeignKey
ALTER TABLE "GscJob" ADD CONSTRAINT "GscJob_dealerId_fkey" FOREIGN KEY ("dealerId") REFERENCES "Dealer"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- Seed the GSC system user (idempotent + invariant-enforcing)
-- The deterministic id='gsc-system-user' is intentional: it lets lookups be
-- stable across environments without an env var.
-- ON CONFLICT DO UPDATE (not DO NOTHING): if a row with this email already
-- exists with isSystem=false, the worker's auth-guard would silently fail.
-- Force the invariant to hold every time this migration runs.
INSERT INTO "User" ("id", "email", "name", "role", "password", "isSystem", "createdAt", "updatedAt")
VALUES (
  'gsc-system-user',
  'gsc-system@aimclear.internal',
  'GSC System',
  'admin',
  NULL,
  TRUE,
  NOW(),
  NOW()
)
ON CONFLICT ("email") DO UPDATE SET
  "isSystem" = TRUE,
  "role" = 'admin',
  "password" = NULL,
  "updatedAt" = NOW();
