CREATE SCHEMA IF NOT EXISTS "public";

CREATE TYPE "ApplicationKind" AS ENUM ('TOUR', 'TRANSFER', 'QUICK_PICK', 'TRAVEL_PLAN');
CREATE TYPE "ApplicationStatus" AS ENUM ('NEW', 'MANAGER_REVIEW', 'WAITING_CUSTOMER', 'CONFIRMED', 'COMPLETED', 'CANCELLED', 'REJECTED');
CREATE TYPE "ApplicationEventType" AS ENUM ('CREATED', 'TELEGRAM_MANAGER_NOTIFIED', 'TELEGRAM_CUSTOMER_NOTIFIED', 'STATUS_CHANGED', 'COMMENT_ADDED', 'CRM_SYNCED', 'DELIVERY_FAILED');
CREATE TYPE "TravelPlanStatus" AS ENUM ('DRAFT', 'READY', 'SUBMITTED', 'CONFIRMED', 'ARCHIVED');
CREATE TYPE "ReminderStatus" AS ENUM ('PENDING', 'PROCESSING', 'SENT', 'CANCELLED', 'FAILED');
CREATE TYPE "OutboxKind" AS ENUM ('TELEGRAM_MANAGER_APPLICATION', 'TELEGRAM_CUSTOMER_CONFIRMATION', 'TELEGRAM_REMINDER', 'CRM_APPLICATION', 'CRM_PLAN');
CREATE TYPE "OutboxStatus" AS ENUM ('PENDING', 'PROCESSING', 'SENT', 'FAILED', 'DEAD_LETTER');

CREATE TABLE "TelegramUser" (
    "id" TEXT NOT NULL,
    "telegramUserId" TEXT NOT NULL,
    "username" TEXT,
    "firstName" TEXT,
    "lastName" TEXT,
    "languageCode" TEXT,
    "allowsWrite" BOOLEAN,
    "lastAuthAt" TIMESTAMP(3) NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    CONSTRAINT "TelegramUser_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "Favorite" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "serviceId" TEXT NOT NULL,
    "serviceKind" TEXT NOT NULL,
    "serviceSnapshot" JSONB,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT "Favorite_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "Application" (
    "id" TEXT NOT NULL,
    "publicId" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "kind" "ApplicationKind" NOT NULL,
    "status" "ApplicationStatus" NOT NULL DEFAULT 'NEW',
    "serviceId" TEXT,
    "serviceKind" TEXT,
    "serviceTitle" TEXT,
    "serviceSnapshot" JSONB,
    "requestedDate" DATE,
    "adults" INTEGER NOT NULL DEFAULT 1,
    "children" INTEGER NOT NULL DEFAULT 0,
    "customerName" TEXT NOT NULL,
    "phone" TEXT,
    "whatsapp" TEXT,
    "hotelOrArea" TEXT,
    "comment" TEXT,
    "managerComment" TEXT,
    "telegramMessageId" TEXT,
    "crmEntityId" TEXT,
    "idempotencyKey" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    CONSTRAINT "Application_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "ApplicationEvent" (
    "id" TEXT NOT NULL,
    "applicationId" TEXT NOT NULL,
    "type" "ApplicationEventType" NOT NULL,
    "actor" TEXT,
    "payload" JSONB,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT "ApplicationEvent_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "TravelPlan" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "applicationId" TEXT,
    "city" TEXT NOT NULL,
    "arrivalDate" DATE NOT NULL,
    "departureDate" DATE NOT NULL,
    "adults" INTEGER NOT NULL DEFAULT 1,
    "children" INTEGER NOT NULL DEFAULT 0,
    "categories" TEXT[],
    "comment" TEXT,
    "status" "TravelPlanStatus" NOT NULL DEFAULT 'DRAFT',
    "submittedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    CONSTRAINT "TravelPlan_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "TravelPlanItem" (
    "id" TEXT NOT NULL,
    "planId" TEXT NOT NULL,
    "serviceId" TEXT NOT NULL,
    "serviceKind" TEXT NOT NULL,
    "serviceTitle" TEXT NOT NULL,
    "serviceSnapshot" JSONB,
    "startDate" DATE NOT NULL,
    "endDate" DATE NOT NULL,
    "durationDays" INTEGER NOT NULL DEFAULT 1,
    "startTime" TEXT,
    "note" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    CONSTRAINT "TravelPlanItem_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "TravelPlanItemDay" (
    "id" TEXT NOT NULL,
    "itemId" TEXT NOT NULL,
    "date" DATE NOT NULL,
    CONSTRAINT "TravelPlanItemDay_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "Reminder" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "planId" TEXT,
    "title" TEXT NOT NULL,
    "message" TEXT NOT NULL,
    "triggerAt" TIMESTAMP(3) NOT NULL,
    "status" "ReminderStatus" NOT NULL DEFAULT 'PENDING',
    "attempts" INTEGER NOT NULL DEFAULT 0,
    "lastError" TEXT,
    "sentAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    CONSTRAINT "Reminder_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "OutboxMessage" (
    "id" TEXT NOT NULL,
    "applicationId" TEXT,
    "kind" "OutboxKind" NOT NULL,
    "status" "OutboxStatus" NOT NULL DEFAULT 'PENDING',
    "payload" JSONB NOT NULL,
    "attempts" INTEGER NOT NULL DEFAULT 0,
    "nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "lastError" TEXT,
    "sentAt" TIMESTAMP(3),
    "lockedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    CONSTRAINT "OutboxMessage_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "TelegramUser_telegramUserId_key" ON "TelegramUser"("telegramUserId");
CREATE INDEX "TelegramUser_createdAt_idx" ON "TelegramUser"("createdAt");
CREATE INDEX "Favorite_userId_createdAt_idx" ON "Favorite"("userId", "createdAt");
CREATE UNIQUE INDEX "Favorite_userId_serviceKind_serviceId_key" ON "Favorite"("userId", "serviceKind", "serviceId");
CREATE UNIQUE INDEX "Application_publicId_key" ON "Application"("publicId");
CREATE INDEX "Application_userId_createdAt_idx" ON "Application"("userId", "createdAt");
CREATE INDEX "Application_status_createdAt_idx" ON "Application"("status", "createdAt");
CREATE INDEX "Application_kind_createdAt_idx" ON "Application"("kind", "createdAt");
CREATE UNIQUE INDEX "Application_userId_idempotencyKey_key" ON "Application"("userId", "idempotencyKey");
CREATE INDEX "ApplicationEvent_applicationId_createdAt_idx" ON "ApplicationEvent"("applicationId", "createdAt");
CREATE INDEX "ApplicationEvent_type_createdAt_idx" ON "ApplicationEvent"("type", "createdAt");
CREATE UNIQUE INDEX "TravelPlan_applicationId_key" ON "TravelPlan"("applicationId");
CREATE INDEX "TravelPlan_userId_createdAt_idx" ON "TravelPlan"("userId", "createdAt");
CREATE INDEX "TravelPlan_status_createdAt_idx" ON "TravelPlan"("status", "createdAt");
CREATE INDEX "TravelPlanItem_planId_startDate_idx" ON "TravelPlanItem"("planId", "startDate");
CREATE UNIQUE INDEX "TravelPlanItem_planId_serviceId_startDate_key" ON "TravelPlanItem"("planId", "serviceId", "startDate");
CREATE INDEX "TravelPlanItemDay_date_idx" ON "TravelPlanItemDay"("date");
CREATE UNIQUE INDEX "TravelPlanItemDay_itemId_date_key" ON "TravelPlanItemDay"("itemId", "date");
CREATE INDEX "Reminder_status_triggerAt_idx" ON "Reminder"("status", "triggerAt");
CREATE INDEX "Reminder_userId_triggerAt_idx" ON "Reminder"("userId", "triggerAt");
CREATE INDEX "OutboxMessage_status_nextAttemptAt_idx" ON "OutboxMessage"("status", "nextAttemptAt");
CREATE INDEX "OutboxMessage_applicationId_createdAt_idx" ON "OutboxMessage"("applicationId", "createdAt");

ALTER TABLE "Favorite" ADD CONSTRAINT "Favorite_userId_fkey" FOREIGN KEY ("userId") REFERENCES "TelegramUser"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Application" ADD CONSTRAINT "Application_userId_fkey" FOREIGN KEY ("userId") REFERENCES "TelegramUser"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "ApplicationEvent" ADD CONSTRAINT "ApplicationEvent_applicationId_fkey" FOREIGN KEY ("applicationId") REFERENCES "Application"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "TravelPlan" ADD CONSTRAINT "TravelPlan_userId_fkey" FOREIGN KEY ("userId") REFERENCES "TelegramUser"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "TravelPlan" ADD CONSTRAINT "TravelPlan_applicationId_fkey" FOREIGN KEY ("applicationId") REFERENCES "Application"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "TravelPlanItem" ADD CONSTRAINT "TravelPlanItem_planId_fkey" FOREIGN KEY ("planId") REFERENCES "TravelPlan"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "TravelPlanItemDay" ADD CONSTRAINT "TravelPlanItemDay_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "TravelPlanItem"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Reminder" ADD CONSTRAINT "Reminder_userId_fkey" FOREIGN KEY ("userId") REFERENCES "TelegramUser"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Reminder" ADD CONSTRAINT "Reminder_planId_fkey" FOREIGN KEY ("planId") REFERENCES "TravelPlan"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "OutboxMessage" ADD CONSTRAINT "OutboxMessage_applicationId_fkey" FOREIGN KEY ("applicationId") REFERENCES "Application"("id") ON DELETE CASCADE ON UPDATE CASCADE;
