import _ from 'lodash'
import { type Repository } from '../src/dataTypes.ts'
import branches from '../src/branches.ts'
import { dateToRfc3339 } from '@11ty/eleventy-plugin-rss'
import flatPatches from '../src/flatPatches.ts'

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

    const slugify = eleventyConfig.getFilter("slugify")

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