CREATE OR REPLACE VIEW optimized_oembed AS 
WITH oembed_data AS (
  SELECT 
    'post' AS type, 
    p.url::TEXT AS url, 
    p.title AS title, 
    p.description AS description, 
    CASE
      WHEN df.filename_disk IS NOT NULL AND df.filename_disk != '' AND df.filename_disk != '/' THEN df.filename_disk
      ELSE (SELECT g.avatar FROM optimized_globals g LIMIT 1)
    END AS image_url,
    p.date AS content_date
  FROM optimized_posts p
  LEFT JOIN directus_files df ON p.image = df.filename_disk
  UNION ALL
  SELECT
    'book' AS type,
    b.url::TEXT AS url,
    b.title AS title,
    b.description AS description,
    CASE
      WHEN b.image IS NOT NULL AND b.image != '' THEN b.image
      ELSE (SELECT g.avatar FROM optimized_globals g LIMIT 1)
    END AS image_url,
    b.date_finished AS content_date
  FROM optimized_books b
  UNION ALL
  SELECT
    'artist' AS type,
    ar.url::TEXT AS url,
    ar.name AS title,
    ar.description AS description,
    CASE
      WHEN ar.image IS NOT NULL AND ar.image != '' THEN ar.image
      ELSE (SELECT g.avatar FROM optimized_globals g LIMIT 1)
    END AS image_url,
    CURRENT_TIMESTAMP AS content_date
  FROM optimized_artists ar
  UNION ALL
  SELECT
    'genre' AS type,
    g.url::TEXT AS url,
    g.name AS title,
    g.description AS description,
    CASE
      WHEN top_artist.image IS NOT NULL AND top_artist.image != '' THEN top_artist.image
      ELSE (SELECT g.avatar FROM optimized_globals g LIMIT 1)
    END AS image_url,
    CURRENT_TIMESTAMP AS content_date
  FROM optimized_genres g
  LEFT JOIN LATERAL (
    SELECT ar.image
    FROM optimized_artists ar
    WHERE (ar.genre->>'id')::bigint = g.id
    ORDER BY ar.total_plays DESC
    LIMIT 1
  ) top_artist ON true
  UNION ALL
  SELECT
    'show' AS type,
    s.url::TEXT AS url,
    s.title AS title,
    s.description AS description,
    CASE
      WHEN s.image IS NOT NULL AND s.image != '' THEN s.image
      ELSE (SELECT g.avatar FROM optimized_globals g LIMIT 1)
    END AS image_url,
    s.last_watched_at AS content_date
  FROM optimized_shows s
  UNION ALL
  SELECT
    'movie' AS type,
    m.url::TEXT AS url,
    m.title AS title,
    m.description AS description,
    CASE
      WHEN m.image IS NOT NULL AND m.image != '' THEN m.image
      ELSE (SELECT g.avatar FROM optimized_globals g LIMIT 1)
    END AS image_url,
    m.last_watched AS content_date
  FROM optimized_movies m
)
SELECT 
  ROW_NUMBER() OVER (ORDER BY url) AS id, 
  * 
FROM 
  oembed_data;
