-- CreateEnum
CREATE TYPE "JobOrderStatus" AS ENUM ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED');

-- CreateTable
CREATE TABLE "JobOrder" (
    "id" TEXT NOT NULL,
    "tenantId" TEXT NOT NULL,
    "orderNumber" TEXT NOT NULL,
    "ticketId" TEXT NOT NULL,
    "jobType" TEXT NOT NULL,
    "description" TEXT,
    "assignedToId" TEXT NOT NULL,
    "status" "JobOrderStatus" NOT NULL DEFAULT 'PENDING',
    "scheduledDate" TIMESTAMP(3),
    "startedAt" TIMESTAMP(3),
    "completedAt" TIMESTAMP(3),
    "outcomeNotes" TEXT,
    "cancelledAt" TIMESTAMP(3),
    "cancelReason" TEXT,
    "createdById" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateIndex
CREATE INDEX "JobOrder_tenantId_idx" ON "JobOrder"("tenantId");

-- CreateIndex
CREATE INDEX "JobOrder_tenantId_ticketId_idx" ON "JobOrder"("tenantId", "ticketId");

-- CreateIndex
CREATE INDEX "JobOrder_tenantId_assignedToId_idx" ON "JobOrder"("tenantId", "assignedToId");

-- CreateIndex
CREATE INDEX "JobOrder_tenantId_status_idx" ON "JobOrder"("tenantId", "status");

-- CreateIndex
CREATE UNIQUE INDEX "JobOrder_tenantId_orderNumber_key" ON "JobOrder"("tenantId", "orderNumber");

-- AddForeignKey
ALTER TABLE "JobOrder" ADD CONSTRAINT "JobOrder_ticketId_fkey" FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "JobOrder" ADD CONSTRAINT "JobOrder_assignedToId_fkey" FOREIGN KEY ("assignedToId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "JobOrder" ADD CONSTRAINT "JobOrder_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
