ALTER TABLE "customers" ADD COLUMN IF NOT EXISTS "memberrelation" bigint;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'customers_memberrelation_memberrelations_id_fk'
    ) THEN
        ALTER TABLE "customers"
            ADD CONSTRAINT "customers_memberrelation_memberrelations_id_fk"
            FOREIGN KEY ("memberrelation")
            REFERENCES "public"."memberrelations"("id")
            ON DELETE no action
            ON UPDATE no action;
    END IF;
END $$;

UPDATE "customers"
SET "memberrelation" = ("infoData"->>'memberrelation')::bigint
WHERE
    "memberrelation" IS NULL
    AND "type" = 'Mitglied'
    AND jsonb_typeof(COALESCE("infoData", '{}'::jsonb)) = 'object'
    AND COALESCE("infoData", '{}'::jsonb) ? 'memberrelation'
    AND ("infoData"->>'memberrelation') ~ '^[0-9]+$';

UPDATE "customers"
SET "infoData" = COALESCE("infoData", '{}'::jsonb) - 'memberrelation'
WHERE
    "type" = 'Mitglied'
    AND jsonb_typeof(COALESCE("infoData", '{}'::jsonb)) = 'object'
    AND COALESCE("infoData", '{}'::jsonb) ? 'memberrelation';
