DO $$
DECLARE
	_path character varying(256) := 'patch-2026_01_20-EmailMessageSendItems';
	_build integer := 15815;
BEGIN
	IF EXISTS (SELECT 1 FROM public."Versions" WHERE "Path" = _path) THEN
		RETURN;
	END IF;

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

	BEGIN
		CREATE TABLE public."EmailMessageSendItems"
		(
			"Id" bigserial, 
			"Timestamp" timestamp without time zone DEFAULT timezone('utc', now()) NOT NULL,
			"UserEmailId" BIGINT not NULL, 
			"NeedImapSave" boolean,
			"Message" varchar null,
			"EmailMessageId" BIGINT NULL,
			"ReplyToId" bigint null,
			"EventId" BIGINT NULL, 
			"ParticipantId" BIGINT NULL, 
			"Type" INT NULL,
			"Status" int NULL,
			"SmtpStatus" int null,
			"SmtpStatusTimestamp" timestamp without time zone,
			"ImapStatus" int null,
			"ImapStatusTimestamp" timestamp without time zone,
			"SmtpTryCount" int null,
			"ImapTryCount" int null,
			"LastSmtpError" character varying(512) NULL,
			"LastImapError" character varying(512) NULL,
			"StatusTimestamp" timestamp without time zone DEFAULT timezone('utc', now()) NOT NULL,
			CONSTRAINT "UIDX_EmailMessageSendItems" UNIQUE ("Id")
		);

		CREATE INDEX IF NOT EXISTS "IDX_EmailMessageSendItems_StatusTimestamp"
			ON public."EmailMessageSendItems" ("UserEmailId", "Status", "StatusTimestamp" DESC);


		INSERT INTO public."Versions" ("Path", "Build") VALUES (_path, 0);

	EXCEPTION
		WHEN OTHERS THEN
			RAISE NOTICE '[ERR] %: %', _path, SQLERRM;
	END;
END;
$$;