-- P5-4483 populate framed prints interior images

BEGIN;

    -- temp lookup table: all products that exists as both poster and framed print
    DROP TABLE IF EXISTS _poster_framed_prints_products;

    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 poster_id, framed_print_id FROM (
        SELECT poster.printid AS poster_id, framed_print.printid AS framed_print_id
        FROM "product-products" products
        LEFT JOIN "product-printproducts" poster ON products.productid = poster.productid AND poster.groupid = 7
        LEFT JOIN "product-printproducts" framed_print ON products.productid = framed_print.productid AND framed_print.groupid = 8
        WHERE poster.productid IS NOT NULL AND framed_print.productid IS NOT NULL
    ) x;


    --temp lookup table: poster room to framed print room
    DROP TABLE IF EXISTS _poster_framed_prints_rooms;

    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%';

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

    -- delete all existing framed prints interiors
    DELETE FROM interiors WHERE print_id IN (
        SELECT printid FROM "product-printproducts" WHERE groupid = 8
    );

    -- 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;


    -- finally delete the temporary tables
    DROP TABLE _poster_framed_prints_products;
    DROP TABLE _poster_framed_prints_rooms;

COMMIT;
