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

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

        BEGIN
            CREATE TABLE IF NOT EXISTS public."FileDlpProcessing"
            (
                "Id"            BIGSERIAL PRIMARY KEY,
                "DocumentId"    BIGINT                      NOT NULL,
                "FileId"        BIGINT                      NOT NULL,
                "CustomerId"    BIGINT                      NULL,
                "Action"        INTEGER                     NOT NULL,
                "DlpSettingsId" BIGINT                      NOT NULL,
                "Status"        INTEGER                     NOT NULL DEFAULT 0,
                "Attempts"      INTEGER                     NOT NULL DEFAULT 0,
                "LastError"     TEXT                        NULL,
                "TaskId"        BIGINT                      NULL,
                "CreatedAtUtc"  TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT timezone('utc', now()),
                "UpdatedAtUtc"  TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT timezone('utc', now())
            );

            -- Индекс на поиск по файлу и действию
            CREATE INDEX IF NOT EXISTS "IDX_FileDlpProcessing_File_Action"
                ON public."FileDlpProcessing" ("DocumentId", "FileId", "Action");

            -- Индекс по статусу (для воркера)
            CREATE INDEX IF NOT EXISTS "IDX_FileDlpProcessing_Status"
                ON public."FileDlpProcessing" ("Status");

            -- Индекс по настройкам DLP (join)
            CREATE INDEX IF NOT EXISTS "IDX_FileDlpProcessing_DlpSettingsId"
                ON public."FileDlpProcessing" ("DlpSettingsId");

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

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

    END;
$$;
