DROP VIEW IF EXISTS v_product_category_with_ancestors;
DROP VIEW IF EXISTS v_hidden_categories;
DROP VIEW IF EXISTS v_category_with_ancestors;
DROP VIEW IF EXISTS v_browsable_published_printproducts_per_market;
DROP VIEW IF EXISTS v_browsable_published_printproducts;

CREATE VIEW v_browsable_published_printproducts AS
    SELECT p.productid, p.path, pp.printid, pp.groupid
    FROM "product-products" p JOIN "product-printproducts" pp USING (productid)
    WHERE visible = 1 and browsable = 1 and publishing_date <= now();
COMMENT ON VIEW v_browsable_published_printproducts IS 'All published print products that are browsable';


CREATE VIEW v_browsable_published_printproducts_per_market AS
    with prints_and_markets as (select v.*, markets.id market_id from v_browsable_published_printproducts v, markets)
    select p.*, pb.id is not null as blacklisted
    from prints_and_markets p
    left join product_blacklist pb on product_id = productid and group_id = groupid and p.market_id = pb.market_id;
COMMENT ON VIEW v_browsable_published_printproducts_per_market IS 'Published, browsable print products with blacklist status';

create view v_category_with_ancestors as
    SELECT c.id, tree.id AS ancestor_id, tree.name
    FROM categories c
    LEFT JOIN categories tree ON tree.lft <= c.lft AND tree.rgt >= c.rgt AND tree.id <> 1;
COMMENT ON VIEW v_category_with_ancestors IS 'List all ancestors for a category, and itself';

create view v_hidden_categories as
    SELECT c.id, c.name FROM categories hidden
    JOIN categories c ON c.lft >= hidden.lft AND c.rgt <= hidden.rgt
    WHERE hidden.id = 1689;
COMMENT ON VIEW v_hidden_categories IS 'All our hidden categories';

create view v_product_category_with_ancestors as
    SELECT DISTINCT pc.product_id, v.ancestor_id AS category_id, v.name
    FROM product_category pc
    LEFT JOIN v_category_with_ancestors v ON pc.category_id = v.id
    LEFT JOIN v_hidden_categories ON v.id = v_hidden_categories.id
    WHERE v_hidden_categories.id IS NULL;
COMMENT ON VIEW v_product_category_with_ancestors
    IS 'Categories assigned to product, including parent categories. Hidden categories excluded';
