import Sandbox from '@nyariv/sandboxjs'
import { fetchLastMagazine } from '@/fetch/magazine'
import {
  PublicationAndNewsletterView,
  NewsletterArchiveItem,
} from './PublicationAndNewsletterView'

export const PublicationAndNewsletter = async () => {
  let archiveData: NewsletterArchiveItem[] = []

  try {
    const response = await fetch(
      'https://s3-eu-west-1.amazonaws.com/files.crsend.com/37000/37866/rss/mailings.js',
      { cache: 'force-cache', next: { revalidate: 3600 } },
    )
    const jsContent = await response.text()

    const sandbox = new Sandbox()
    const scope: { cr_archive: NewsletterArchiveItem[] } = { cr_archive: [] }
    const exec = sandbox.compile(jsContent)
    exec(scope).run()

    archiveData = scope.cr_archive.slice(0, 3)
  } catch {
    console.error(
      'Could not fetch newsletters. Please check PublicationAndNewsletter component',
    )
  }

  const magazine = await fetchLastMagazine()
  const magazineUrl =
    magazine && typeof magazine.document === 'object'
      ? magazine.document.url || undefined
      : undefined
  const magazineCover =
    magazine && typeof magazine.cover === 'object' ? magazine.cover : undefined

  return (
    <PublicationAndNewsletterView
      archiveData={archiveData}
      magazineUrl={magazineUrl}
      magazineCover={magazineCover}
    />
  )
}
