-- CreateTable (idempotent)
CREATE TABLE IF NOT EXISTS "OpportunityStage" (
    "uid" TEXT NOT NULL,
    "id" INTEGER NOT NULL,
    "name" TEXT NOT NULL,
    "seqNbr" INTEGER,
    "funnelColor" TEXT,
    "updatedById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "OpportunityStage_pkey" PRIMARY KEY ("uid")
);

-- CreateIndex (idempotent)
CREATE UNIQUE INDEX IF NOT EXISTS "OpportunityStage_id_key" ON "OpportunityStage"("id");

-- AlterTable: drop old columns if they exist, add stageId if it doesn't
DO $$
BEGIN
  IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'Opportunity' AND column_name = 'stageName') THEN
    ALTER TABLE "Opportunity" DROP COLUMN "stageName";
  END IF;
  IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'Opportunity' AND column_name = 'stageCwId') THEN
    ALTER TABLE "Opportunity" DROP COLUMN "stageCwId";
  END IF;
  IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'Opportunity' AND column_name = 'stageId') THEN
    ALTER TABLE "Opportunity" ADD COLUMN "stageId" INTEGER;
  END IF;
END $$;

-- Nullify any stageId values that reference non-existent OpportunityStage rows
UPDATE "Opportunity" SET "stageId" = NULL
WHERE "stageId" IS NOT NULL
  AND "stageId" NOT IN (SELECT "id" FROM "OpportunityStage");

-- AddForeignKey (skip if already exists)
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.table_constraints
    WHERE constraint_name = 'Opportunity_stageId_fkey'
  ) THEN
    ALTER TABLE "Opportunity" ADD CONSTRAINT "Opportunity_stageId_fkey"
      FOREIGN KEY ("stageId") REFERENCES "OpportunityStage"("id") ON DELETE SET NULL ON UPDATE CASCADE;
  END IF;
END $$;
