-- New pricing system

drop table if exists price_segments cascade;
create table price_segments (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL UNIQUE
);
INSERT INTO price_segments (name) VALUES ('BASE'), ('A'), ('B'), ('C'), ('OWN-IMAGE');
INSERT INTO price_segments (name) VALUES ('custom1'), ('designer-b');

drop table if exists prices_wallpaper_m2 cascade;
CREATE TABLE prices_wallpaper_m2 (
      id SERIAL PRIMARY KEY,
      material_id INT REFERENCES "product-materials" (materialid) NOT NULL,
      segment_id INT REFERENCES price_segments (id) NOT NULL,
      market_id INT REFERENCES markets (id) NOT NULL,
      price NUMERIC NOT NULL CHECK (price > 0),
      UNIQUE (material_id, segment_id, market_id)
);

drop table if exists prices_external_products cascade;
CREATE TABLE prices_external_products (
    id SERIAL PRIMARY KEY,
    external_product_id TEXT REFERENCES external_print_products (external_product_id) NOT NULL,
    segment_id INT REFERENCES price_segments (id) NOT NULL,
    market_id INT REFERENCES markets (id) NOT NULL,
    price NUMERIC NOT NULL CHECK (price > 0),
    UNIQUE (external_product_id, segment_id, market_id)
);

drop table if exists price_segmentations cascade;
CREATE TABLE price_segmentations (
    product_id INT REFERENCES "product-products" (productid),
    designer_id INT REFERENCES designers (designerid),
    custom BOOLEAN DEFAULT false,
    segment_id INT REFERENCES price_segments (id) NOT NULL,
    CONSTRAINT either_product_or_designer CHECK ( (product_id IS NULL AND designer_id IS NOT NULL) OR (product_id IS NOT NULL AND designer_id IS NULL) ),
    UNIQUE (product_id, custom),
    UNIQUE (designer_id, custom)
);
-- Todo: will add constraint that segment_id cannot be 'OWN-IMAGE'

drop view if exists v_price_product_segments cascade;
create view v_price_product_segments as
with duplicates as (
    -- First read all actual segment assignments from table
    select
        products.productid,
        segment_id,
        (case when custom and product_id is not null then 5 when custom and designer_id is not null then 4 when not custom and product_id is not null then 3 else 2 end) as priority
    from
        "product-products" products join price_segmentations on productid = product_id or designerid = designer_id
    UNION
    -- Then add the fallback assignment to BASE segment, with lowest priority
    select products.productid, 1 as segment_id, 1 as priority from "product-products" products
) select
    -- Remove duplicate segment assignments
    productid, segment_id, max(priority) as priority from duplicates group by productid, segment_id;


drop view if exists v_listprices_new;
create view v_listprices_new as
select
    printid printproduct_id,
    markets.id market_id,
    CASE
        WHEN groupid in (1,3) THEN (
            select price
            from v_price_product_segments v
            join prices_wallpaper_m2 p on v.segment_id = p.segment_id and material_id = 1
            where v.productid = prints.productid and market_id = markets.id
            order by priority desc
            limit 1
        )
        WHEN groupid = 2 THEN (
            select price
            from v_price_product_segments v
            join prices_external_products p on v.segment_id = p.segment_id
                and external_product_id = 'canvas_200x300-mm-8x12-inch_canvas_wood-fsc-slim_4-0_ver'
            where v.productid = prints.productid and market_id = markets.id
            order by priority desc
            limit 1
        )
        WHEN groupid in (7,8) THEN (
            select price
            from v_price_product_segments v
            join prices_external_products p on v.segment_id = p.segment_id
                and external_product_id = 'flat_250x250-mm-10x10-inch_200-gsm-80lb-uncoated_4-0_ver'
            where v.productid = prints.productid and market_id = markets.id
            order by priority desc
            limit 1
        )
        END as listprice
from
    "product-printproducts" prints,
    markets
;


--------------------------------------
-- Fake price data for development
-- segment 1 (BASE), standard material. copy listprice from a non-designer wallpaper
INSERT INTO prices_wallpaper_m2 (material_id, segment_id, market_id, price)
    select 1, 1, market_id, round(listprice)
    from v_listprices where printproduct_id = (
        select printid from "product-products" join "product-printproducts" using (productid)
        where designerid is null and browsable = 1 and groupid = 1 limit 1
    ) order by market_id;
-- premium, product, segment 1 (1.09 * standard listprice)
INSERT INTO prices_wallpaper_m2 (material_id, segment_id, market_id, price)
    SELECT 4, 1, market_id, round(price * 1.09) FROM prices_wallpaper_m2 WHERE segment_id = 1 and material_id = 1;
-- standard, product, segment 2 (2 * standard listprice)
INSERT INTO prices_wallpaper_m2 (material_id, segment_id, market_id, price)
    SELECT 1, 2, market_id, round(price * 2) FROM prices_wallpaper_m2 WHERE segment_id = 1 and material_id = 1;
-- premium, product, segment 2 (2.29 * standard listprice)
INSERT INTO prices_wallpaper_m2 (material_id, segment_id, market_id, price)
    SELECT 4, 2, market_id, round(price * 2.29) FROM prices_wallpaper_m2 WHERE segment_id = 1 and material_id = 1;
-- standard, product, segment 3 (1.15 * standard listprice)
INSERT INTO prices_wallpaper_m2 (material_id, segment_id, market_id, price)
    SELECT 1, 3, market_id, round(price * 1.15) FROM prices_wallpaper_m2 WHERE segment_id = 1 and material_id = 1;
-- premium, product, segment 3 (1.19 * standard listprice)
INSERT INTO prices_wallpaper_m2 (material_id, segment_id, market_id, price)
    SELECT 4, 3, market_id, round(price * 1.19) FROM prices_wallpaper_m2 WHERE segment_id = 1 and material_id = 1;
-- standard, product, segment 4 (0.9 * standard listprice)
INSERT INTO prices_wallpaper_m2 (material_id, segment_id, market_id, price)
    SELECT 1, 4, market_id, round(price * 0.9) FROM prices_wallpaper_m2 WHERE segment_id = 1 and material_id = 1;
-- premium, product, segment 4 (0.92 * standard listprice)
INSERT INTO prices_wallpaper_m2 (material_id, segment_id, market_id, price)
    SELECT 4, 4, market_id, round(price * 0.92) FROM prices_wallpaper_m2 WHERE segment_id = 1 and material_id = 1;
-- External products
-- segment 1 (base), normal products
insert into prices_external_products (external_product_id, segment_id, market_id, price)
select external_product_id, 1, markets.id, round(price_sek * price_adjustment * vat * exchange_rate)
from external_print_products, markets join "product-currencies" on currency = iso3char
order by markets.id, external_product_id;
-- segment 2-4 (A,B,C)
insert into prices_external_products (external_product_id, segment_id, market_id, price)
select external_product_id, 2, market_id, round(price * 2) from prices_external_products where segment_id = 1;
insert into prices_external_products (external_product_id, segment_id, market_id, price)
select external_product_id, 3, market_id, round(price * 1.2) from prices_external_products where segment_id = 1;
insert into prices_external_products (external_product_id, segment_id, market_id, price)
select external_product_id, 4, market_id, round(price * 0.9) from prices_external_products where segment_id = 1;

insert into prices_wallpaper_m2(material_id, segment_id, market_id, price)
    select material_id, (select id from price_segments where name = 'OWN-IMAGE'), market_id, price
        from prices_wallpaper_m2 where segment_id = 1;
update prices_wallpaper_m2 set price = price * 3
    where segment_id = (select id from price_segments where name = 'OWN-IMAGE') and market_id = 1;
insert into prices_external_products (external_product_id, segment_id, market_id, price)
    select external_product_id, (select id from price_segments where name = 'OWN-IMAGE'), market_id, price
        from prices_external_products where segment_id = 1;
update prices_external_products set price = price * 3
    where segment_id = (select id from price_segments where name = 'OWN-IMAGE') and market_id = 1;

insert into price_segmentations (product_id, designer_id, custom, segment_id)
values
    (62542, null, false, 1),
    (62542, null, true, 6),
    (null, 249, true, 7),
    (null, 249, false, 1),
    (null, 182, false, 2),
    (46596, null, false, 3),
    (46880, null, false, 2),
    (null, 123, false, 2)
;

drop table if exists price_file_imports cascade;
create table price_file_imports (
    id serial primary key,
    inserted timestamp with time zone not null DEFAULT now(),
    comment text,
    csv_content text,
    active boolean default false,
    deleted timestamp with time zone DEFAULT null,
    meta jsonb
);

drop type if exists price_file_imports_history_type cascade;
CREATE TYPE price_file_imports_history_type AS ENUM ('activated', 'deactivated');

drop table if exists price_file_imports_history cascade;
create table price_file_imports_history (
   import_id int REFERENCES price_file_imports (id) NOT NULL,
   type price_file_imports_history_type NOT NULL,
   date timestamp with time zone not null DEFAULT now()
);

drop table if exists prices_other_products cascade;
CREATE TABLE prices_other_products (
    market_id INT REFERENCES markets (id) PRIMARY KEY,
    wallpaper_kit_price NUMERIC NOT NULL CHECK (wallpaper_kit_price > 0),
    wallpaper_sample_price NUMERIC NOT NULL CHECK (wallpaper_kit_price > 0),
    updated timestamp with time zone default now()
);
CREATE TRIGGER updated_timestamp BEFORE UPDATE ON prices_other_products FOR EACH ROW EXECUTE PROCEDURE updated_timestamp();

INSERT INTO prices_other_products (market_id, wallpaper_kit_price, wallpaper_sample_price) select id, 500, 50 from markets order by id;
update prices_other_products set wallpaper_kit_price = 19 where market_id in (select id from markets where name in ('GB','GLOBAL','PL'));
update prices_other_products set wallpaper_kit_price = 199 where market_id in (select id from markets where name in ('DK','NO','SE'));
update prices_other_products set wallpaper_kit_price = 21 where market_id in (select id from markets where name in ('AT','CH','IE','IT','LU','SG','US'));
update prices_other_products set wallpaper_kit_price = 22 where market_id in (select id from markets where name in ('DE','FR'));
update prices_other_products set wallpaper_kit_price = 23 where market_id in (select id from markets where name in ('EE','NL'));
update prices_other_products set wallpaper_kit_price = 24 where market_id in (select id from markets where name in ('BE','CA','ES','FI'));
update prices_other_products set wallpaper_kit_price = 26 where market_id = (select id from markets where name = 'AU');
update prices_other_products set wallpaper_sample_price = 2 where market_id in
    (select id from markets where name in ('US','SG','CH','GB','FI','GLOBAL','DE','NL','AT','ES','FR','PL','IT','BE','IE','EE','LU'));
update prices_other_products set wallpaper_sample_price = 3 where market_id in (select id from markets where name in ('CA','AU'));
update prices_other_products set wallpaper_sample_price = 19 where market_id in (select id from markets where name in ('SE','NO','DK'));

-- New price on SE to make testing easier:
update prices_other_products set wallpaper_kit_price = 49, wallpaper_sample_price = 29 where market_id = 1;
