DO
$$
    DECLARE
        _path character varying(256) := 'patch-2025_11_21-FileDlpCache';
    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
            IF NOT EXISTS(
                SELECT 1
                FROM information_schema.tables
                WHERE table_schema = 'public'
                  AND table_name = 'FileDlpCache'
            ) THEN

                CREATE TABLE public."FileDlpCache"
                (
                    "Id"               BIGSERIAL PRIMARY KEY,
                    "Hash"             TEXT                        NOT NULL,
                    "Size"             BIGINT                      NOT NULL,
                    "CustomerId"       BIGINT                      NULL,
                    "Action"           INTEGER                     NOT NULL,
                    "DlpSettingsId"    BIGINT                      NOT NULL,
                    "Status"           INTEGER                     NOT NULL,
                    "LastError"        TEXT                        NULL,
                    "LastCheckedAtUtc" TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT timezone('utc', now())
                );

                CREATE UNIQUE INDEX IF NOT EXISTS "UQ_FileDlpCache_Signature"
                    ON public."FileDlpCache" ("Hash", "Size", "CustomerId", "Action", "DlpSettingsId");
            END IF;

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

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

    END;
$$;
