-- Consolidate duplicate clerk gift rows and enforce uniqueness

-- Normalize null gift counts
UPDATE play_clerk_gift_info
SET giff_number = 0
WHERE giff_number IS NULL;

UPDATE play_custom_gift_info
SET giff_number = 0
WHERE giff_number IS NULL;

-- Remove invalid rows lacking required identifiers
DELETE FROM play_clerk_gift_info
WHERE clerk_id IS NULL OR giff_id IS NULL;

DELETE FROM play_custom_gift_info
WHERE custom_id IS NULL OR giff_id IS NULL;

-- Merge duplicate clerk gift rows and keep a single survivor per key
UPDATE play_clerk_gift_info t
JOIN (
    SELECT COALESCE(MAX(CASE WHEN deleted = 0 THEN id END), MAX(id)) AS keep_id,
           tenant_id,
           clerk_id,
           giff_id,
           SUM(giff_number) AS total
    FROM play_clerk_gift_info
    GROUP BY tenant_id, clerk_id, giff_id
    HAVING COUNT(*) > 1
) agg ON t.id = agg.keep_id
SET t.giff_number = agg.total;

DELETE dup
FROM play_clerk_gift_info dup
JOIN (
    SELECT COALESCE(MAX(CASE WHEN deleted = 0 THEN id END), MAX(id)) AS keep_id,
           tenant_id,
           clerk_id,
           giff_id
    FROM play_clerk_gift_info
    GROUP BY tenant_id, clerk_id, giff_id
    HAVING COUNT(*) > 1
) keepers
  ON dup.tenant_id = keepers.tenant_id
 AND dup.clerk_id = keepers.clerk_id
 AND dup.giff_id = keepers.giff_id
WHERE dup.id <> keepers.keep_id;

-- Merge duplicate customer gift rows and keep a single survivor per key
UPDATE play_custom_gift_info t
JOIN (
    SELECT COALESCE(MAX(CASE WHEN deleted = 0 THEN id END), MAX(id)) AS keep_id,
           tenant_id,
           custom_id,
           giff_id,
           SUM(giff_number) AS total
    FROM play_custom_gift_info
    GROUP BY tenant_id, custom_id, giff_id
    HAVING COUNT(*) > 1
) agg ON t.id = agg.keep_id
SET t.giff_number = agg.total;

DELETE dup
FROM play_custom_gift_info dup
JOIN (
    SELECT COALESCE(MAX(CASE WHEN deleted = 0 THEN id END), MAX(id)) AS keep_id,
           tenant_id,
           custom_id,
           giff_id
    FROM play_custom_gift_info
    GROUP BY tenant_id, custom_id, giff_id
    HAVING COUNT(*) > 1
) keepers
  ON dup.tenant_id = keepers.tenant_id
 AND dup.custom_id = keepers.custom_id
 AND dup.giff_id = keepers.giff_id
WHERE dup.id <> keepers.keep_id;

-- Enforce non-null identifiers and counts
ALTER TABLE play_clerk_gift_info
    MODIFY clerk_id varchar(32) NOT NULL,
    MODIFY giff_id varchar(32) NOT NULL,
    MODIFY giff_number bigint NOT NULL DEFAULT 0;

ALTER TABLE play_custom_gift_info
    MODIFY custom_id varchar(32) NOT NULL,
    MODIFY giff_id varchar(32) NOT NULL,
    MODIFY giff_number bigint NOT NULL DEFAULT 0;

-- Create unique constraints for tenant scoped gift counters
ALTER TABLE play_clerk_gift_info
    ADD CONSTRAINT uk_play_clerk_gift UNIQUE KEY (tenant_id, clerk_id, giff_id);

ALTER TABLE play_custom_gift_info
    ADD CONSTRAINT uk_play_custom_gift UNIQUE KEY (tenant_id, custom_id, giff_id);
