DO $$ 
	DECLARE _path character varying(256) = 'patch-2024-12-03-UserEmailSettings-UserEmailId';

	BEGIN
		IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Path"=_path) THEN
			RETURN;
		END IF;

		IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Build">=14592) THEN
			RETURN;
		END IF;

		BEGIN
            		ALTER TABLE public."UserEmailSettings" ADD "UserEmailId" BIGINT;

            		UPDATE public."UserEmailSettings" SET "UserEmailId"=(SELECT "Id" FROM public."UserEmails" where 								"UserId"=public."UserEmailSettings"."UserId" LIMIT 1);
			DELETE FROM public."UserEmailSettings" where "UserEmailId" IS NULL;

			CREATE TABLE public."UserEmailSettingsNew"
			(
				"Id" bigserial, 
				"UserId" BIGINT NOT NULL, 
				"UserEmailId" BIGINT NOT NULL,
				"Json" text NULL DEFAULT '{}',
				"Timestamp" timestamp without time zone DEFAULT timezone('utc', now())  NOT NULL,
				CONSTRAINT "UIDX_UserEmailSettingsUserEmailId" UNIQUE ("UserEmailId")
			);

			CREATE INDEX "IDX_UserEmailSettings_UserId_New" ON public."UserEmailSettingsNew" USING btree ("UserId");

			INSERT INTO public."UserEmailSettingsNew" ("UserId", "UserEmailId","Json")
			SELECT "UserId", "UserEmailId","Json" FROM public."UserEmailSettings";
			DROP TABLE public."UserEmailSettings";
			ALTER TABLE public."UserEmailSettingsNew" RENAME TO "UserEmailSettings";

			

 			INSERT INTO public."Versions" ("Path", "Build") VALUES (_path, 0);
			EXCEPTION
				WHEN OTHERS THEN RAISE NOTICE '[ERR] patch-2024-12-03-UserEmailSettings-UserEmailId: %', SQLERRM;
		END;
	END;
$$