ALTER TABLE "milestones" ADD COLUMN IF NOT EXISTS "pmMemberId" TEXT;

CREATE TABLE IF NOT EXISTS "milestone_assignees" (
    "milestoneId" TEXT NOT NULL,
    "memberId" TEXT NOT NULL,
    CONSTRAINT "milestone_assignees_pkey" PRIMARY KEY ("milestoneId","memberId")
);

CREATE INDEX IF NOT EXISTS "milestone_assignees_memberId_idx" ON "milestone_assignees"("memberId");
CREATE INDEX IF NOT EXISTS "milestones_pmMemberId_idx" ON "milestones"("pmMemberId");

DO $$ BEGIN
  ALTER TABLE "milestones" ADD CONSTRAINT "milestones_pmMemberId_fkey"
    FOREIGN KEY ("pmMemberId") REFERENCES "team_members"("id") ON DELETE SET NULL ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;

DO $$ BEGIN
  ALTER TABLE "milestone_assignees" ADD CONSTRAINT "milestone_assignees_milestoneId_fkey"
    FOREIGN KEY ("milestoneId") REFERENCES "milestones"("id") ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;

DO $$ BEGIN
  ALTER TABLE "milestone_assignees" ADD CONSTRAINT "milestone_assignees_memberId_fkey"
    FOREIGN KEY ("memberId") REFERENCES "team_members"("id") ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
