-- Add new AuthType enum values
DO $$ BEGIN
  ALTER TYPE "AuthType" ADD VALUE IF NOT EXISTS 'SMTP';
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

DO $$ BEGIN
  ALTER TYPE "AuthType" ADD VALUE IF NOT EXISTS 'POP3';
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

-- Platform: add orgId, nameId and unique composite; drop unique on code
ALTER TABLE "Platform" ADD COLUMN IF NOT EXISTS "orgId" TEXT;
ALTER TABLE "Platform" ADD COLUMN IF NOT EXISTS "nameId" TEXT;

-- For existing rows, set empty strings to satisfy not-null, then enforce
UPDATE "Platform" SET "orgId" = COALESCE("orgId", '') WHERE "orgId" IS NULL;
UPDATE "Platform" SET "nameId" = COALESCE("nameId", '') WHERE "nameId" IS NULL;

ALTER TABLE "Platform" ALTER COLUMN "orgId" SET NOT NULL;
ALTER TABLE "Platform" ALTER COLUMN "nameId" SET NOT NULL;

-- Drop previous unique constraint on code if exists
DO $$ BEGIN
  DROP INDEX IF EXISTS "Platform_code_key";
EXCEPTION WHEN undefined_object THEN NULL; END $$;

-- Create new composite unique (orgId,nameId)
DO $$ BEGIN
  CREATE UNIQUE INDEX IF NOT EXISTS "Platform_orgId_nameId_key" ON "Platform"("orgId", "nameId");
EXCEPTION WHEN duplicate_table THEN NULL; END $$;

-- Secret: allow multiple per AuthMethod by name; add tags
ALTER TABLE "Secret" ADD COLUMN IF NOT EXISTS "name" TEXT;
ALTER TABLE "Secret" ADD COLUMN IF NOT EXISTS "tags" TEXT[] DEFAULT '{}';

-- Backfill existing rows
UPDATE "Secret" SET "name" = COALESCE("name", '') WHERE "name" IS NULL;
UPDATE "Secret" SET "tags" = COALESCE("tags", '{}') WHERE "tags" IS NULL;

-- Drop previous unique on authMethodId (1:1)
DO $$ BEGIN
  DROP INDEX IF EXISTS "Secret_authMethodId_key";
EXCEPTION WHEN undefined_object THEN NULL; END $$;

-- Create new unique on (authMethodId, name)
DO $$ BEGIN
  CREATE UNIQUE INDEX IF NOT EXISTS "Secret_authMethodId_name_key" ON "Secret"("authMethodId", "name");
EXCEPTION WHEN duplicate_table THEN NULL; END $$;

-- Enforce not null
ALTER TABLE "Secret" ALTER COLUMN "name" SET NOT NULL;
ALTER TABLE "Secret" ALTER COLUMN "tags" SET NOT NULL;
