DROP MATERIALIZED VIEW IF EXISTS v_esales_categorytree_i18n;
-- REFRESH MATERIALIZED VIEW v_esales_categorytree_i18n;

CREATE MATERIALIZED VIEW v_esales_categorytree_i18n AS
SELECT	*,
		-- Remove diacritics and other stuff
		REGEXP_REPLACE(
			UNACCENT(REPLACE(REPLACE(path, ' ', '_'), '&', 'and')),
			'[^\w/\-]', '', 'g'
		) AS path_translated
  FROM	(
			SELECT	c.id,
					(
						SELECT	id
						  FROM	categories s
						 WHERE	s.lft < c.lft AND s.rgt > c.rgt
						 ORDER	BY s.rgt-c.rgt ASC
						 LIMIT	1
					) AS parent_id,
					locale_id,
					locale,
					c.name,
					(
						SELECT	LOWER(array_to_string(array_agg(main.parent_name), '/')) AS path
						  FROM	(
								SELECT	node.id,
										(
											SELECT	name
											  FROM	category_texts
											 WHERE	locale_id = c.locale_id
											   AND	category_id = parent.id
										) AS parent_name
								  FROM	categories node,
										categories parent
								 WHERE	node.lft BETWEEN parent.lft AND parent.rgt
								   AND	node.id = c.id
								 ORDER	BY parent.lft
							) main
						 GROUP	BY main.id
					) AS path,
					CASE c.rgt - c.lft
						WHEN 1 THEN 1
						ELSE 0
					END AS is_leaf,
					(
						SELECT	count(*) - 1
						  FROM	categories node,
								categories parent
						 WHERE	node.lft BETWEEN parent.lft AND parent.rgt AND node.id = c.id
					) AS depth,
					(
						SELECT	count(*) - 1
						  FROM	categories c1
						 WHERE	c1.lft BETWEEN c.lft AND c.rgt
					) AS child_count,
					c.lft,
					c.rgt
			  FROM	(
				SELECT	c.id,
						s.id AS locale_id,
						s.value AS locale,
						LOWER(s_t.name) AS name,
						rgt,
						lft
				  FROM	locales s
				  JOIN	category_texts s_t ON s.id = s_t.locale_id
				  JOIN	categories c ON s_t.category_id = c.id
				 ORDER	BY s.id, c.lft
			  ) c
) main;

-- DROP INDEX v_esales_categorytree_i18n_id_locale_id;
CREATE UNIQUE INDEX v_esales_categorytree_i18n_id_locale_id
  ON v_esales_categorytree_i18n (id, locale_id);
