INSERT INTO "users" (
    "id",
    "slug",
    "display_name",
    "is_default",
    "created_at",
    "updated_at"
)
VALUES (
    gen_random_uuid(),
    'default-owner',
    'Default Owner',
    true,
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
)
ON CONFLICT ("slug") DO UPDATE
SET
    "display_name" = EXCLUDED."display_name",
    "is_default" = true,
    "updated_at" = CURRENT_TIMESTAMP;

DROP INDEX IF EXISTS "artwork_assets_user_id_sha256_key";

WITH "tracked_artwork_owner" AS (
    SELECT DISTINCT ON ("t"."artwork_asset_id")
        "t"."artwork_asset_id" AS "artwork_id",
        "t"."user_id"
    FROM "tracks" AS "t"
    WHERE "t"."artwork_asset_id" IS NOT NULL
    ORDER BY "t"."artwork_asset_id", "t"."created_at" ASC, "t"."id" ASC
)
UPDATE "artwork_assets" AS "aa"
SET "user_id" = "tracked_artwork_owner"."user_id"
FROM "tracked_artwork_owner"
WHERE "aa"."id" = "tracked_artwork_owner"."artwork_id"
  AND "aa"."user_id" IS NULL;

UPDATE "artwork_assets"
SET "user_id" = (SELECT "id" FROM "users" WHERE "slug" = 'default-owner')
WHERE "user_id" IS NULL;

WITH "ranked_artwork" AS (
    SELECT
        "id",
        "user_id",
        "sha256",
        FIRST_VALUE("id") OVER (
            PARTITION BY "user_id", "sha256"
            ORDER BY "created_at" ASC, "id" ASC
        ) AS "canonical_id",
        ROW_NUMBER() OVER (
            PARTITION BY "user_id", "sha256"
            ORDER BY "created_at" ASC, "id" ASC
        ) AS "row_number"
    FROM "artwork_assets"
),
"duplicate_artwork" AS (
    SELECT "id", "canonical_id"
    FROM "ranked_artwork"
    WHERE "row_number" > 1
)
UPDATE "tracks" AS "t"
SET "artwork_asset_id" = "d"."canonical_id"
FROM "duplicate_artwork" AS "d"
WHERE "t"."artwork_asset_id" = "d"."id";

WITH "ranked_artwork" AS (
    SELECT
        "id",
        ROW_NUMBER() OVER (
            PARTITION BY "user_id", "sha256"
            ORDER BY "created_at" ASC, "id" ASC
        ) AS "row_number"
    FROM "artwork_assets"
),
"duplicate_artwork" AS (
    SELECT "id"
    FROM "ranked_artwork"
    WHERE "row_number" > 1
)
DELETE FROM "artwork_assets" AS "aa"
USING "duplicate_artwork" AS "d"
WHERE "aa"."id" = "d"."id";

ALTER TABLE "artwork_assets"
ALTER COLUMN "user_id" SET NOT NULL;

CREATE UNIQUE INDEX "artwork_assets_user_id_sha256_key"
ON "artwork_assets"("user_id", "sha256");
