CREATE OR REPLACE VIEW optimized_syndication AS
WITH syndication_data AS (
  SELECT
    p.date AS content_date,
    json_build_object(
      'title', CONCAT('📝 ', p.title, ' ', (
        SELECT array_to_string(
          array_agg('#' || initcap(replace(trim(tag_part), ' ', ''))),
          ' '
        )
        FROM unnest(p.tags) AS t(name),
             regexp_split_to_table(t.name, '\s*&\s*') AS tag_part
      )),
      'description', p.description,
      'url', p.url,
      'image', p.image,
      'date', p.date
    ) AS feed
  FROM optimized_posts p
  UNION ALL
  SELECT
    l.date AS content_date,
    json_build_object(
      'title', CONCAT('🔗 ', l.title, CASE
        WHEN l.mastodon IS NOT NULL THEN ' via @' || split_part(l.mastodon, '@', 2) || '@' || split_part(split_part(l.mastodon, 'https://', 2), '/', 1)
        ELSE CONCAT(' via ', l.name)
      END, ' ', (
        SELECT array_to_string(
          array_agg('#' || initcap(replace(trim(tag_part), ' ', ''))),
          ' '
        )
        FROM unnest(l.tags) AS t(name),
             regexp_split_to_table(t.name, '\s*&\s*') AS tag_part
      )),
      'description', l.description,
      'url', l.link,
      'date', l.date
    ) AS feed
  FROM optimized_links l
  UNION ALL
  SELECT
    b.date_finished AS content_date,
    CASE
      WHEN LOWER(b.status) = 'finished' THEN
        json_build_object(
          'title', CONCAT('📖 ', b.title, CASE
            WHEN b.rating IS NOT NULL THEN ' (' || b.rating || ')' ELSE '' END, ' ', (
              SELECT array_to_string(
                array_agg('#' || initcap(replace(trim(tag_part), ' ', ''))),
                ' '
              )
              FROM unnest(b.tags) AS t(name),
                   regexp_split_to_table(t.name, '\s*&\s*') AS tag_part
            )
          ),
          'description', b.description,
          'url', b.url,
          'image', b.image,
          'date', b.date_finished
        )
      ELSE NULL
    END AS feed
  FROM optimized_books b
  UNION ALL
  SELECT
    m.last_watched AS content_date,
    CASE
      WHEN m.last_watched IS NOT NULL THEN
        json_build_object(
          'title', CONCAT('🎥 ', m.title, CASE
            WHEN m.rating IS NOT NULL THEN ' (' || m.rating || ')' ELSE '' END, ' ', (
              SELECT array_to_string(
                array_agg('#' || initcap(replace(trim(tag_part), ' ', ''))),
                ' '
              )
              FROM unnest(m.tags) AS t(name),
                   regexp_split_to_table(t.name, '\s*&\s*') AS tag_part
            )
          ),
          'description', m.description,
          'url', m.url,
          'image', m.image,
          'date', m.last_watched
        )
      ELSE NULL
    END AS feed
  FROM optimized_movies m
)
SELECT feed
FROM syndication_data
WHERE feed IS NOT NULL
ORDER BY content_date DESC
LIMIT 3;
