BEGIN;

DELETE FROM oa_conflicts  WHERE created_by = 'dedupWf' and reltype = 'suggested';
DELETE FROM oa_duplicates WHERE created_by = 'dedupWf' and reltype = 'suggested';
DELETE FROM organizations WHERE created_by = 'dedupWf' and modified_by = 'dedupWf'; 

-- FIX IMPORT DATA
UPDATE tmp_dedup_events SET oa_country = 'UNKNOWN' WHERE oa_country = '' OR oa_country IS NULL;

-- NEW ORGANIZATIONS
INSERT INTO organizations(id, name, country, status, created_by, modified_by) 
SELECT oa_original_id, oa_name, oa_country, 'suggested', 'dedupWf', 'dedupWf' 
FROM tmp_dedup_events 
WHERE oa_original_id NOT LIKE 'openorgs\_\_\_\_::%' AND oa_original_id = local_id
ON CONFLICT DO NOTHING;

INSERT INTO organizations(id, name, country, status, created_by, modified_by) 
SELECT oa_original_id, oa_name, oa_country, 'duplicate', 'dedupWf', 'dedupWf' 
FROM tmp_dedup_events 
WHERE oa_original_id NOT LIKE 'openorgs\_\_\_\_::%' AND oa_original_id != local_id
ON CONFLICT DO NOTHING;


INSERT INTO acronyms(id, acronym) SELECT oa_original_id, oa_acronym FROM tmp_dedup_events WHERE oa_original_id NOT LIKE 'openorgs\_\_\_\_::%' ON CONFLICT DO NOTHING;
INSERT INTO urls(id, url) SELECT oa_original_id, oa_url FROM tmp_dedup_events WHERE oa_original_id NOT LIKE 'openorgs\_\_\_\_::%' ON CONFLICT DO NOTHING;

-- DUPLICATES
INSERT INTO oa_duplicates (local_id, oa_original_id, oa_collectedfrom, created_by, modified_by)
SELECT local_id, oa_original_id, oa_collectedfrom, 'dedupWf', 'dedupWf'
FROM tmp_dedup_events
WHERE local_id IS NOT NULL AND local_id != '' AND oa_original_id NOT LIKE 'openorgs\_\_\_\_::%' AND local_id != oa_original_id
ON CONFLICT DO NOTHING;


-- CONFLICTS
INSERT INTO oa_conflicts (id1, id2, idgroup, created_by, modified_by)
SELECT local_id, oa_original_id, group_id, 'dedupWf', 'dedupWf'
FROM tmp_dedup_events
WHERE local_id LIKE 'openorgs\_\_\_\_::%' AND oa_original_id LIKE 'openorgs\_\_\_\_::%' AND local_id != oa_original_id AND group_id IS NOT NULL AND group_id != ''
ON CONFLICT DO NOTHING;


COMMIT;
