CREATE OR REPLACE VIEW optimized_week_music AS
SELECT
  json_build_object(
    'week_artists',
    (
      SELECT
        json_agg(
          a
          ORDER BY
            a.plays DESC
        )
      FROM
        (
          SELECT
            *
          FROM
            week_artists
          ORDER BY
            plays DESC
          LIMIT
            8
        ) a
    ),
    'week_albums',
    (
      SELECT
        json_agg(
          al
          ORDER BY
            al.plays DESC
        )
      FROM
        (
          SELECT
            *
          FROM
            week_albums
          ORDER BY
            plays DESC
          LIMIT
            8
        ) al
    ),
    'week_genres',
    (
      SELECT
        json_agg(
          g
          ORDER BY
            g.plays DESC
        )
      FROM
        (
          SELECT
            *
          FROM
            week_genres
          ORDER BY
            plays DESC
          LIMIT
            5
        ) g
    ),
    'recent_tracks',
    (
      SELECT
        json_agg(
          r
          ORDER BY
            r.listened_at DESC
        )
      FROM
        (
          SELECT
            *
          FROM
            recent_tracks
          ORDER BY
            listened_at DESC
          LIMIT
            10
        ) r
    ),
    'week_summary',
    (
      SELECT
        json_build_object(
          'total_tracks',
          (
            SELECT
              COUNT(*)
            FROM
              week_tracks
          ),
          'total_artists',
          (
            SELECT
              COUNT(*)
            FROM
              week_artists
          ),
          'total_albums',
          (
            SELECT
              COUNT(*)
            FROM
              week_albums
          )
        )
    )
  ) AS week_music;
