-- The init migration shipped without EmailTemplate (it was originally added
-- via `prisma db push`), so a fresh shadow-DB rebuild has no table for the
-- subsequent `drop_email_template_enabled` migration to alter. Backfill the
-- table here. Idempotent so this is a no-op on dev/prod where the table
-- already exists.

-- CreateTable
CREATE TABLE IF NOT EXISTS "EmailTemplate" (
    "id" TEXT NOT NULL,
    "ownerId" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "enabled" BOOLEAN NOT NULL DEFAULT true,
    "subject" TEXT NOT NULL,
    "body" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateIndex
CREATE UNIQUE INDEX IF NOT EXISTS "EmailTemplate_ownerId_type_key" ON "EmailTemplate"("ownerId", "type");

-- CreateIndex
CREATE INDEX IF NOT EXISTS "EmailTemplate_ownerId_idx" ON "EmailTemplate"("ownerId");

-- AddForeignKey (wrapped to make it idempotent — Postgres ADD CONSTRAINT
-- has no IF NOT EXISTS clause until Postgres 18 / specific patches).
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'EmailTemplate_ownerId_fkey'
    ) THEN
        ALTER TABLE "EmailTemplate"
        ADD CONSTRAINT "EmailTemplate_ownerId_fkey"
        FOREIGN KEY ("ownerId") REFERENCES "Owner"("id")
        ON DELETE RESTRICT ON UPDATE CASCADE;
    END IF;
END $$;
