DO $$
    DECLARE _path character varying(256) = 'patch-2025_09_09-telegram_usertelegram_and_settings';
    BEGIN
        IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Path"=_path) THEN
            RETURN;
        END IF;

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

        BEGIN
            CREATE TABLE IF NOT EXISTS public."UserTelegram" (
                "UserId" bigint PRIMARY KEY,
                "ChatId" bigint NOT NULL,
                "LinkedAt" timestamptz DEFAULT now() NOT NULL,
                "IsEnabled" boolean NOT NULL DEFAULT true
            );

            CREATE TABLE IF NOT EXISTS public."TelegramSettings" (
                "CustomerId" integer PRIMARY KEY,
                "BotToken" varchar(128) NOT NULL,
                "IsEnabled" boolean DEFAULT false NOT NULL,
                "Timestamp" timestamptz DEFAULT now() NOT NULL
            );

            CREATE UNIQUE INDEX IF NOT EXISTS ux_UserTelegram_UserId ON public."UserTelegram"("UserId");
            CREATE INDEX IF NOT EXISTS ix_UserTelegram_ChatId ON public."UserTelegram"("ChatId");

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