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, 
    COALESCE(NULLIF(p.metadata->>'open_graph_image', ''), (SELECT metadata->>'open_graph_image' FROM optimized_globals LIMIT 1)) AS image_url,
    p.date AS content_date
  FROM optimized_posts p
  UNION ALL
  SELECT
    'book' AS type,
    b.url::TEXT AS url,
    b.title AS title,
    b.description AS description,
    COALESCE(NULLIF(b.metadata->>'open_graph_image', ''), (SELECT metadata->>'open_graph_image' FROM optimized_globals LIMIT 1)) 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,
    COALESCE(NULLIF(ar.metadata->>'open_graph_image', ''), (SELECT metadata->>'open_graph_image' FROM optimized_globals LIMIT 1)) 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,
    COALESCE(NULLIF(g.metadata->>'open_graph_image', ''), (SELECT metadata->>'open_graph_image' FROM optimized_globals LIMIT 1)) AS image_url,
    CURRENT_TIMESTAMP AS content_date
  FROM optimized_genres g
  UNION ALL
  SELECT
    'show' AS type,
    s.url::TEXT AS url,
    s.title AS title,
    s.description AS description,
    COALESCE(NULLIF(s.metadata->>'open_graph_image', ''), (SELECT metadata->>'open_graph_image' FROM optimized_globals LIMIT 1)) 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,
    COALESCE(NULLIF(m.metadata->>'open_graph_image', ''), (SELECT metadata->>'open_graph_image' FROM optimized_globals LIMIT 1)) 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;
