-- P5-5107: make all poster products availible as framed prints

CREATE TABLE tmp (
    productid integer
);


-- all posters that are not available as framed prints
INSERT INTO tmp
SELECT posters.productid FROM "product-printproducts" posters
LEFT JOIN "product-printproducts" framed_prints ON posters.productid = framed_prints.productid AND framed_prints.groupid = 8
WHERE posters.groupid = 7 AND framed_prints.printid IS NULL;


-- create framed prints products
INSERT INTO "product-printproducts" (productid, groupid, collectionid, typeid)
SELECT productid, 8, 1, 1 FROM tmp;


-- create interior images
CREATE TABLE _poster_framed_prints_products (
    poster_id integer,
    framed_print_id integer
);

INSERT INTO _poster_framed_prints_products (poster_id, framed_print_id)
SELECT posters.printid, framed_prints.printid FROM tmp
JOIN "product-printproducts" posters ON tmp.productid = posters.productid AND posters.groupid = 7
JOIN "product-printproducts" framed_prints ON tmp.productid = framed_prints.productid AND framed_prints.groupid = 8;


--temp lookup table: poster room to framed print room
CREATE TABLE _poster_framed_prints_rooms (
    poster_room_id integer,
    framed_print_room_id integer
);

INSERT INTO _poster_framed_prints_rooms
SELECT poster_rooms.id, framed_print_rooms.id FROM rooms poster_rooms
JOIN rooms framed_print_rooms ON framed_print_rooms.name LIKE REPLACE(poster_rooms.name, 'poster', 'framed-print')
WHERE poster_rooms.name LIKE '%poster%';


-- insert new interior images (based on posters)
INSERT INTO interiors (print_id, room_id, position)
SELECT * FROM (
    SELECT
        _poster_framed_prints_products.framed_print_id AS print_id,
        _poster_framed_prints_rooms.framed_print_room_id AS room_id,
        poster_interiors.position AS position
    FROM _poster_framed_prints_products
    JOIN interiors poster_interiors ON poster_interiors.print_id = _poster_framed_prints_products.poster_id
    JOIN _poster_framed_prints_rooms ON poster_interiors.room_id = _poster_framed_prints_rooms.poster_room_id
) x;

-- drop temporary tables
DROP TABLE tmp;
DROP TABLE _poster_framed_prints_products;
DROP TABLE _poster_framed_prints_rooms;
