CREATE OR REPLACE VIEW week_albums AS
SELECT
  ol.album_name,
  ol.artist_name,
  COUNT(*) AS plays,
  ol.album_art,
  ol.artist_url,
  json_build_object(
    'title', ol.album_name,
    'image', ol.album_art,
    'url', ol.artist_url,
    'alt', CONCAT(ol.album_name, ' by ', ol.artist_name),
    'subtext', ol.artist_name
  ) AS grid,
  json_build_object(
    'open_graph_image',
    CASE
      WHEN ol.opengraph_image_album IS NOT NULL AND ol.opengraph_image_album != '' AND ol.opengraph_image_album != '/' THEN ol.opengraph_image_album
      ELSE NULL
    END
  ) AS metadata
FROM
  optimized_listens ol
WHERE
  TO_TIMESTAMP(ol.listened_at) >= NOW() - INTERVAL '7 days'
GROUP BY
  ol.album_name,
  ol.artist_name,
  ol.album_art,
  ol.artist_url,
  ol.opengraph_image_album
ORDER BY
  plays DESC;
