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 s.uri
           FROM v_interior_image_urls s
          WHERE products.productid = s.productid AND (s.product_group = ANY (ARRAY[1, 3]))
          ORDER BY s."position"
         LIMIT 1) AS interior_primary_uri,
   CASE WHEN EXISTS (
    SELECT 1 FROM "product-printproducts" s WHERE s.groupid = 3 AND s.productid = products.productid
   )
       THEN TRUE
       ELSE FALSE
   END AS repeating_pattern
   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;
