CREATE OR REPLACE VIEW optimized_albums AS
SELECT
  al.name AS name,
  al.release_year,
  to_char(al.total_plays, 'FM999,999,999,999') AS total_plays,
  al.total_plays AS total_plays_raw,
  ar.name_string AS artist_name,
  ar.slug AS artist_url,
  CONCAT(globals.cdn_url, '/', df_album.filename_disk) AS image,
  json_build_object(
    'title',
    al.name,
    'image',
    CONCAT(globals.cdn_url, '/', df_album.filename_disk),
    'url',
    ar.slug,
    'alt',
    CONCAT('Cover for ', al.name, ' by ', ar.name_string),
    'subtext',
    CONCAT(
      to_char(al.total_plays, 'FM999,999,999,999'),
      ' plays'
    )
  ) AS grid,
  json_build_object(
    'title',
    al.name,
    'artist',
    ar.name_string,
    'plays',
    to_char(al.total_plays, 'FM999,999,999,999'),
    'image',
    CONCAT(globals.cdn_url, '/', df_album.filename_disk),
    'url',
    ar.slug,
    'year',
    al.release_year,
    'alt',
    CONCAT('Cover for ', al.name, ' by ', ar.name_string)
  ) AS table
FROM
  albums al
  LEFT JOIN artists ar ON al.artist = ar.id
  LEFT JOIN directus_files df_album ON al.art = df_album.id
  CROSS JOIN optimized_globals globals
GROUP BY
  al.id,
  ar.name_string,
  ar.slug,
  df_album.filename_disk,
  globals.cdn_url;
