import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
import type { APIContext } from 'astro';

export async function GET(context: APIContext) {
  const episodes = await getCollection('episodes');
  const sortedEpisodes = episodes.sort(
    (a, b) =>
      new Date(b.data.pubDate).getTime() - new Date(a.data.pubDate).getTime()
  );

  return rss({
    title: 'The Computer Guru Show',
    description:
      'Helping you deal with all of your technology needs while treating you like a person in the process.',
    site: context.site!.toString(),
    items: sortedEpisodes.map((ep) => ({
      title: ep.data.title,
      pubDate: ep.data.pubDate,
      description: ep.body?.substring(0, 300) || ep.data.title,
      link: `/episodes/${ep.id}`,
      customData: `<enclosure url="${ep.data.audioUrl}" length="${ep.data.audioSize}" type="audio/mpeg"/>
        <itunes:duration>${ep.data.duration}</itunes:duration>
        <itunes:episode>${ep.data.episode}</itunes:episode>
        <itunes:season>${ep.data.season}</itunes:season>`,
    })),
    customData: `<language>en-us</language>
      <itunes:author>Mike Swanson</itunes:author>
      <itunes:category text="Technology"/>
      <itunes:image href="https://radio.azcomputerguru.com/og-image.jpg"/>
      <itunes:explicit>false</itunes:explicit>
      <itunes:type>episodic</itunes:type>`,
    xmlns: {
      itunes: 'http://www.itunes.com/dtds/podcast-1.0.dtd',
    },
  });
}
