-- P5-4335 replace canvas interior images

BEGIN;

    -- temp lookup table: all products that exists as both canvas and poster
    DROP TABLE IF EXISTS _poster_canvas_products;

    CREATE TABLE _poster_canvas_products (
        canvas_print_id integer,
        poster_print_id integer
    );

    -- populate the table with values
    INSERT INTO _poster_canvas_products (canvas_print_id, poster_print_id)
    SELECT canvas_print_id, poster_print_id FROM (
        SELECT canvas.printid AS canvas_print_id, poster.printid AS poster_print_id
        FROM "product-products" products
        LEFT JOIN "product-printproducts" canvas ON products.productid = canvas.productid AND canvas.groupid = 2
        LEFT JOIN "product-printproducts" poster ON products.productid = poster.productid AND poster.groupid = 7
        WHERE canvas.productid IS NOT NULL AND poster.productid IS NOT NULL
    ) x;


    --temp lookup table: poster_room to canvas_room
    DROP TABLE IF EXISTS _poster_canvas_rooms;

    CREATE TABLE _poster_canvas_rooms (
        poster_room_id integer,
        canvas_room_id integer
    );

    INSERT INTO _poster_canvas_rooms
    SELECT poster_rooms.id, canvas_rooms.id FROM rooms poster_rooms
    JOIN rooms canvas_rooms ON canvas_rooms.name LIKE REPLACE(poster_rooms.name, 'poster', 'painting')
    WHERE poster_rooms.name LIKE '%poster%';


    ----------------------------------------------------------------------------------------------------------------


    -- delete interior images from all canvases that also exists as posters. Keep own uploaded interiors
    DELETE FROM interiors WHERE
        print_id IN (SELECT canvas_print_id FROM _poster_canvas_products)
        AND room_id IN (SELECT id FROM rooms WHERE name LIKE '%painting%');


    -- -- insert new interior images (based on the images used by posters)
    INSERT INTO interiors (print_id, room_id, position)
    SELECT * FROM (
        SELECT
            _poster_canvas_products.canvas_print_id as print_id,
            _poster_canvas_rooms.canvas_room_id as room_id,
            poster_interiors.position as position
        FROM _poster_canvas_products
        JOIN interiors poster_interiors ON poster_interiors.print_id = _poster_canvas_products.poster_print_id
        JOIN _poster_canvas_rooms ON poster_interiors.room_id = _poster_canvas_rooms.poster_room_id
    ) x;


    -- move own uploaded images last
    UPDATE interiors i1 SET
        position = (
            SELECT max(position) + 1
            FROM interiors i2
            WHERE i1.print_id = i2.print_id
        )
    WHERE i1.room_id IS NULL AND i1.print_id IN (SELECT canvas_print_id from _poster_canvas_products);


    -- finally delete the temporary tables
    DROP TABLE _poster_canvas_products;
    DROP TABLE _poster_canvas_rooms;
COMMIT;
