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

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

        BEGIN
            -- Очистка существующих дублей
            WITH ranked AS (
                SELECT
                    "Id",
                    ROW_NUMBER() OVER (
                        PARTITION BY "OwnerId", "Uid",
                            COALESCE("RecurrenceDt", '0001-01-01'::timestamp without time zone)
                        ORDER BY
                            CASE WHEN "OriginalId" > 0 THEN 0 ELSE 1 END,
                            CASE "SourceType" WHEN 0 THEN 0 WHEN 2 THEN 1 WHEN 3 THEN 2 WHEN 1 THEN 3 ELSE 4 END,
                            CASE WHEN "TimeZoneId" IS NULL THEN 1 ELSE 0 END,
                            CASE WHEN "HasParticipant" THEN 0 ELSE 1 END, 
                            COALESCE("Timestamp", timezone('utc', now())) DESC,
                            "Id" DESC
                        ) AS rn
                FROM public."EventDetails"
            )
            DELETE FROM public."EventDetails" ed
                USING ranked r
            WHERE ed."Id" = r."Id"
              AND r.rn > 1;

            CREATE UNIQUE INDEX IF NOT EXISTS ux_eventdetails_owner_uid_nullrec
                ON public."EventDetails" ("OwnerId", "Uid")
                WHERE "RecurrenceDt" IS NULL;

            CREATE UNIQUE INDEX IF NOT EXISTS ux_eventdetails_owner_uid_recurr
                ON public."EventDetails" ("OwnerId", "Uid", "RecurrenceDt")
                WHERE "RecurrenceDt" IS NOT NULL;

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

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