-- Create ad_subst copies of specified ads
-- Set disp_class of original ad to 10

CREATE TEMPORARY SEQUENCE ad_id_serial;
SELECT SETVAL('ad_id_serial', MAX(ad_id)) FROM ad;

CREATE TEMPORARY SEQUENCE ad_nm_id_serial;
SELECT SETVAL('ad_nm_id_serial', MAX(nm_id)) FROM ad_nm;

CREATE TEMPORARY TABLE ad_to_hide AS
SELECT
    NEXTVAL('ad_id_serial') AS ad_id,
    p_ad_id,
    level_kind,
    disp_class,
    search_class,
    isocode,
    subcode,
    ad_id AS g_ad_id
FROM ad
WHERE ad_id IN
(
    1444278542, -- Donetsk region
    1443781345  -- Luhansk region
);

CREATE TEMPORARY TABLE ad_to_hide_nm AS
SELECT
    NEXTVAL('ad_nm_id_serial') AS nm_id,
    ad_to_hide.ad_id,
    ad_nm.lang,
    ad_nm.extlang,
    ad_nm.script,
    ad_nm.region,
    ad_nm.variant,
    ad_nm.is_local,
    ad_nm.is_auto,
    ad_nm.name,
    ad_nm.name_type
FROM ad_to_hide
JOIN ad_nm ON (ad_to_hide.g_ad_id = ad_nm.ad_id);


INSERT INTO ad
SELECT * FROM ad_to_hide;

INSERT INTO ad_nm
SELECT * FROM ad_to_hide_nm;

UPDATE ad
SET disp_class = 10
WHERE ad_id IN
(
    SELECT g_ad_id FROM ad_to_hide
);

INSERT INTO ad_excl
SELECT
    g_ad_id AS t_ad_id,
    g_ad_id AS e_ad_id
FROM ad_to_hide;

INSERT INTO ad_isocode
SELECT
    ad_to_hide.ad_id,
    ad_isocode.isocode
FROM ad_to_hide
JOIN ad_isocode ON (ad_to_hide.g_ad_id = ad_isocode.ad_id)
ON CONFLICT DO NOTHING;

INSERT INTO ad_source
SELECT
    ad_to_hide.ad_id,
    ad_source.source_type_id,
    ad_source.source_id
FROM ad_to_hide
JOIN ad_source ON (ad_to_hide.g_ad_id = ad_source.ad_id)
ON CONFLICT DO NOTHING;

DELETE FROM ad_recognition
WHERE ad_id IN
(
    SELECT g_ad_id FROM ad_to_hide
);

INSERT INTO ad_recognition
SELECT
    g_ad_id AS ad_id,
    'RU' AS isocode
FROM ad_to_hide;

INSERT INTO ad_recognition
SELECT
    ad_id,
    '001' AS isocode
FROM ad_to_hide;
