-- Migration: Add all missing schema elements not covered by previous migrations
-- This brings the database fully in line with prisma/schema.prisma
-- Uses IF NOT EXISTS / DO $$ guards for idempotent execution

-- =============================================================================
-- 1. MISSING TABLE: WizardTemplate
-- =============================================================================

CREATE TABLE IF NOT EXISTS "WizardTemplate" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "description" TEXT,
    "config" JSONB NOT NULL,
    "isGlobal" BOOLEAN NOT NULL DEFAULT false,
    "programId" TEXT,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

CREATE INDEX IF NOT EXISTS "WizardTemplate_programId_idx" ON "WizardTemplate"("programId");
CREATE INDEX IF NOT EXISTS "WizardTemplate_isGlobal_idx" ON "WizardTemplate"("isGlobal");

DO $$ BEGIN
    ALTER TABLE "WizardTemplate" ADD CONSTRAINT "WizardTemplate_programId_fkey"
        FOREIGN KEY ("programId") REFERENCES "Program"("id") ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

DO $$ BEGIN
    ALTER TABLE "WizardTemplate" ADD CONSTRAINT "WizardTemplate_createdBy_fkey"
        FOREIGN KEY ("createdBy") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

-- =============================================================================
-- 2. MISSING COLUMNS ON SpecialAward: eligibility job tracking fields
-- =============================================================================

ALTER TABLE "SpecialAward" ADD COLUMN IF NOT EXISTS "eligibilityJobStatus" TEXT;
ALTER TABLE "SpecialAward" ADD COLUMN IF NOT EXISTS "eligibilityJobTotal" INTEGER;
ALTER TABLE "SpecialAward" ADD COLUMN IF NOT EXISTS "eligibilityJobDone" INTEGER;
ALTER TABLE "SpecialAward" ADD COLUMN IF NOT EXISTS "eligibilityJobError" TEXT;
ALTER TABLE "SpecialAward" ADD COLUMN IF NOT EXISTS "eligibilityJobStarted" TIMESTAMP(3);

-- =============================================================================
-- 3. Project.referralSource: Already in init migration. No action needed.
--    Round.slug: Already in init migration. No action needed.
-- =============================================================================

-- =============================================================================
-- 5. MISSING INDEXES
-- =============================================================================

-- 5a. Assignment: @@index([projectId, userId])
CREATE INDEX IF NOT EXISTS "Assignment_projectId_userId_idx" ON "Assignment"("projectId", "userId");

-- 5b. AuditLog: @@index([sessionId])
CREATE INDEX IF NOT EXISTS "AuditLog_sessionId_idx" ON "AuditLog"("sessionId");

-- 5c. ProjectFile: @@index([projectId, roundId])
CREATE INDEX IF NOT EXISTS "ProjectFile_projectId_roundId_idx" ON "ProjectFile"("projectId", "roundId");

-- 5d. MessageRecipient: @@index([userId])
CREATE INDEX IF NOT EXISTS "MessageRecipient_userId_idx" ON "MessageRecipient"("userId");

-- 5e. MessageRecipient: @@unique([messageId, userId, channel])
CREATE UNIQUE INDEX IF NOT EXISTS "MessageRecipient_messageId_userId_channel_key" ON "MessageRecipient"("messageId", "userId", "channel");

-- 5f. AwardEligibility: @@index([awardId, eligible]) - composite index
CREATE INDEX IF NOT EXISTS "AwardEligibility_awardId_eligible_idx" ON "AwardEligibility"("awardId", "eligible");

-- =============================================================================
-- 6. REMOVE STALE INDEX: Message_scheduledAt_idx
--    The schema does NOT have @@index([scheduledAt]) on Message.
--    The add_15_features migration created it, but the schema doesn't list it.
--    Leaving it as-is since it's harmless and could be useful.
-- =============================================================================

-- =============================================================================
-- 7. VERIFY: All models from add_15_features are present
--    DigestLog, RoundTemplate, MentorNote, MentorMilestone,
--    MentorMilestoneCompletion, Message, MessageTemplate, MessageRecipient,
--    Webhook, WebhookDelivery, EvaluationDiscussion, DiscussionComment
--    -> All confirmed created in 20260205223133_add_15_features migration.
--    -> All FKs confirmed in add_15_features + 20260208000000_add_missing_fks_indexes.
-- =============================================================================

-- =============================================================================
-- 8. VERIFY: Existing tables from init and subsequent migrations
--    All core tables (User, Account, Session, VerificationToken, Program, Round,
--    EvaluationForm, Project, ProjectFile, Assignment, Evaluation, GracePeriod,
--    SystemSettings, AuditLog, AIUsageLog, NotificationLog, InAppNotification,
--    NotificationEmailSetting, LearningResource, ResourceAccess, Partner,
--    ExpertiseTag, ProjectTag, LiveVotingSession, LiveVote, TeamMember,
--    MentorAssignment, FilteringRule, FilteringResult, FilteringJob,
--    AssignmentJob, TaggingJob, SpecialAward, AwardEligibility, AwardJuror,
--    AwardVote, ReminderLog, ConflictOfInterest, EvaluationSummary,
--    ProjectStatusHistory, MentorMessage, FileRequirement)
--    -> All confirmed present in migrations.
-- =============================================================================

-- =============================================================================
-- SUMMARY OF CHANGES IN THIS MIGRATION:
--
-- NEW TABLE:
--   - WizardTemplate (with programId FK, createdBy FK, indexes)
--
-- NEW COLUMNS:
--   - SpecialAward.eligibilityJobStatus (TEXT, nullable)
--   - SpecialAward.eligibilityJobTotal (INTEGER, nullable)
--   - SpecialAward.eligibilityJobDone (INTEGER, nullable)
--   - SpecialAward.eligibilityJobError (TEXT, nullable)
--   - SpecialAward.eligibilityJobStarted (TIMESTAMP, nullable)
--
-- NEW INDEXES:
--   - Assignment_projectId_userId_idx
--   - AuditLog_sessionId_idx
--   - ProjectFile_projectId_roundId_idx
--   - MessageRecipient_userId_idx
--   - MessageRecipient_messageId_userId_channel_key (UNIQUE)
--   - AwardEligibility_awardId_eligible_idx
--   - WizardTemplate_programId_idx
--   - WizardTemplate_isGlobal_idx
--
-- NEW FOREIGN KEYS:
--   - WizardTemplate_programId_fkey -> Program(id) ON DELETE CASCADE
--   - WizardTemplate_createdBy_fkey -> User(id) ON DELETE RESTRICT
-- =============================================================================
