-- AlterTable: Add missionId column if it doesn't exist
DO $$ 
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns 
        WHERE table_name = 'Calendar' AND column_name = 'missionId'
    ) THEN
        ALTER TABLE "Calendar" ADD COLUMN "missionId" TEXT;
    END IF;
END $$;

-- CreateTable: Create CalendarSync table if it doesn't exist
CREATE TABLE IF NOT EXISTS "CalendarSync" (
    "id" TEXT NOT NULL,
    "calendarId" TEXT NOT NULL,
    "mailCredentialId" TEXT,
    "provider" TEXT NOT NULL,
    "externalCalendarId" TEXT,
    "externalCalendarUrl" TEXT,
    "syncEnabled" BOOLEAN NOT NULL DEFAULT true,
    "lastSyncAt" TIMESTAMP(3),
    "syncFrequency" INTEGER NOT NULL DEFAULT 15,
    "lastSyncError" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateIndex
CREATE UNIQUE INDEX IF NOT EXISTS "CalendarSync_calendarId_key" ON "CalendarSync"("calendarId");

-- CreateIndex
CREATE INDEX IF NOT EXISTS "CalendarSync_calendarId_idx" ON "CalendarSync"("calendarId");

-- CreateIndex
CREATE INDEX IF NOT EXISTS "CalendarSync_mailCredentialId_idx" ON "CalendarSync"("mailCredentialId");

-- CreateIndex
CREATE INDEX IF NOT EXISTS "CalendarSync_provider_idx" ON "CalendarSync"("provider");

-- CreateIndex
CREATE INDEX IF NOT EXISTS "Calendar_missionId_idx" ON "Calendar"("missionId");

-- AddForeignKey: Add Calendar_missionId_fkey if it doesn't exist
DO $$ 
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'Calendar_missionId_fkey'
    ) THEN
        ALTER TABLE "Calendar" ADD CONSTRAINT "Calendar_missionId_fkey" FOREIGN KEY ("missionId") REFERENCES "Mission"("id") ON DELETE SET NULL ON UPDATE CASCADE;
    END IF;
END $$;

-- AddForeignKey: Add CalendarSync_calendarId_fkey if it doesn't exist
DO $$ 
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'CalendarSync_calendarId_fkey'
    ) THEN
        ALTER TABLE "CalendarSync" ADD CONSTRAINT "CalendarSync_calendarId_fkey" FOREIGN KEY ("calendarId") REFERENCES "Calendar"("id") ON DELETE CASCADE ON UPDATE CASCADE;
    END IF;
END $$;

-- AddForeignKey: Add CalendarSync_mailCredentialId_fkey if it doesn't exist
DO $$ 
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'CalendarSync_mailCredentialId_fkey'
    ) THEN
        ALTER TABLE "CalendarSync" ADD CONSTRAINT "CalendarSync_mailCredentialId_fkey" FOREIGN KEY ("mailCredentialId") REFERENCES "MailCredentials"("id") ON DELETE SET NULL ON UPDATE CASCADE;
    END IF;
END $$;
