import m from 'mithril'
import render from 'mithril-node-render'
import { type Repository } from '../src/dataTypes.ts'
import getFlatRels from '../src/flatRels.ts'
import { dateToRfc3339 } from '@11ty/eleventy-plugin-rss'
import flatPatches from '../src/flatPatches.ts'

export default async (
  eleventyConfig: any,
) => {
  return (data) => {
    const flatRel: ReturnType<typeof getFlatRels>[0] = data.flatRel
    const currentRepo: Repository = data.currentRepo
    const currentRel: Repository['branches'][0] = data.currentRel
    const currentRelCommits: Awaited<ReturnType<typeof flatPatches>> = data.currentRelCommits

    const slugify = eleventyConfig.getFilter("slugify")

    return render([
      m.trust('<?xml version="1.0" encoding="utf-8"?>'),
      m('feed', {xmlns: "http://www.w3.org/2005/Atom"}, [
        m('title', `Latest patches in ${flatRel.relName}`),
        m.trust(`<link href="${ data.reposConfig.baseUrl + '/repos/' + slugify(flatRel.repoName) + `/${flatRel.type}/` + slugify(flatRel.relName) + '/commits.xml'}" rel="self" />`),
        m.trust(`<link href="${data.reposConfig.baseUrl + '/repos/' + slugify(flatRel.repoName) + `/${flatRel.type}/` + slugify(flatRel.relName)}" />`),
        m('updated', dateToRfc3339(currentRepo.commits.get(currentRel.sha).date)),
        m('id', data.reposConfig.baseUrl),
        m('author',
          m('name', `${currentRepo.name} contributors`)
        ),
        currentRelCommits.map((commit) => {
          const commitUrl = data.reposConfig.baseUrl + '/repos/' + slugify(flatRel.repoName) + `/${flatRel.type}/` + slugify(flatRel.relName) + '/commits/' + commit.commit.hash
          return m('entry', [
            m('title', commit.commit.message.split('\n')[0]),
            m('author', m('name', commit.commit.author)),
            m.trust(`<link href="${commitUrl}" />`),
            m('updated', dateToRfc3339(commit.commit.date)),
            m('id', commitUrl),
            m('content', {type: "text"}, commit.commit.message),
          ])
        })
      ])
    ])
  }
}
