-- v0.10.0 — Location spine (Release A, additive)
-- Adds the shared hierarchical Location tree and a nullable Plant.locationId.
-- Plant.zone is intentionally KEPT during the dual-write/dual-read window and
-- is dropped in a later migration (Release B) once prod is verified.
-- The cuid backfill (distinct zone strings → Location rows) runs in
-- prisma/scripts/backfill-locations.ts right after `migrate deploy`.

-- CreateEnum
CREATE TYPE "LocationKind" AS ENUM ('AREA', 'BUILDING', 'ROOM', 'STORAGE', 'OTHER');

-- CreateTable
CREATE TABLE "Location" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "kind" "LocationKind" NOT NULL DEFAULT 'AREA',
    "parentId" TEXT,
    "path" TEXT,
    "notes" TEXT,
    "qrSlug" TEXT,
    "active" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateIndex
CREATE UNIQUE INDEX "Location_qrSlug_key" ON "Location"("qrSlug");
CREATE INDEX "Location_parentId_idx" ON "Location"("parentId");
CREATE INDEX "Location_kind_idx" ON "Location"("kind");
CREATE INDEX "Location_active_idx" ON "Location"("active");

-- AddForeignKey
ALTER TABLE "Location" ADD CONSTRAINT "Location_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "Location"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AlterTable: add Plant.locationId (keep zone)
ALTER TABLE "Plant" ADD COLUMN "locationId" TEXT;

-- CreateIndex
CREATE INDEX "Plant_locationId_idx" ON "Plant"("locationId");

-- AddForeignKey
ALTER TABLE "Plant" ADD CONSTRAINT "Plant_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "Location"("id") ON DELETE SET NULL ON UPDATE CASCADE;
