-- View: public.v_analytics_products

DROP VIEW IF EXISTS public.v_analytics_products;

CREATE VIEW public.v_analytics_products
 AS
 SELECT products.productid AS product_id,
    products.path AS product_path,
    products.visible,
    products.browsable,
    products.inserted AS product_inserted,
    products.updated AS product_updated,
    designers.designerid AS designer_id,
    designers.name AS designer_name,
    products.ref1,
    products.ref2,
    products.ref3,
    artno.value AS artno,
    name.value AS product_name,
    width.value::integer AS width,
    height.value::integer AS height,
    copyright.value AS copyright,
    batch.value AS batch,
    COALESCE(products.updated, products.inserted) AS last_updated,
    (
        SELECT si.id
          FROM interiors si
         WHERE si.print_id IN (
            SELECT printid
              FROM "product-printproducts" spp
             WHERE products.productid = spp.productid
               AND groupid IN (
                    1, -- photo-wallpaper
                    3  -- wallpaper
               )
         )
         ORDER BY position
         LIMIT 1
    ) AS interior_primary
   FROM "product-products" products
     LEFT JOIN designers ON products.designerid = designers.designerid
     LEFT JOIN "product-products_fields" artno ON artno.fieldid = 1 AND artno.productid = products.productid
     LEFT JOIN "product-products_fields" name ON name.fieldid = 2 AND name.productid = products.productid
     LEFT JOIN "product-products_fields" width ON width.fieldid = 5 AND width.productid = products.productid
     LEFT JOIN "product-products_fields" height ON height.fieldid = 3 AND height.productid = products.productid
     LEFT JOIN "product-products_fields" copyright ON copyright.fieldid = 25 AND copyright.productid = products.productid
     LEFT JOIN "product-products_fields" batch ON batch.fieldid = 36 AND batch.productid = products.productid;

GRANT SELECT ON TABLE public.v_analytics_products TO datastudio;
GRANT SELECT ON TABLE public.v_analytics_products TO funnel;
