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

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

        BEGIN
            CREATE TABLE IF NOT EXISTS public."FileSharePending"
            (
                "Id"           BIGSERIAL PRIMARY KEY,
                "DocumentId"   BIGINT                      NOT NULL,
                "FileId"       BIGINT                      NOT NULL,
                "CustomerId"   BIGINT                      NULL,
                "Action"       INTEGER                     NOT NULL,
                "RequestJson"  TEXT                        NOT NULL,
                "Status"       INTEGER                     NOT NULL DEFAULT 0,
                "LastError"    TEXT                        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_FileSharePending_File_Action"
                ON public."FileSharePending" ("DocumentId", "FileId", "Action");

            CREATE INDEX IF NOT EXISTS "IDX_FileSharePending_Status"
                ON public."FileSharePending" ("Status");

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

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

    END;
$$;
