import type { Metadata } from "next"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getAnnouncements } from "@/modules/announcements/data-access"
import { getGrades } from "@/modules/school/data-access"
import { getAdminClasses } from "@/modules/classes/data-access"
import { AdminAnnouncementsView } from "@/modules/announcements/components/admin-announcements-view"
import { getSearchParam, type SearchParams } from "@/shared/lib/utils"
import type { AnnouncementStatus } from "@/modules/announcements/types"

export const dynamic = "force-dynamic"

export async function generateMetadata(): Promise<Metadata> {
  const t = await getTranslations("announcements")
  return {
    title: t("title.adminList"),
    description: t("description.adminList"),
  }
}

const isValidStatus = (v?: string): v is AnnouncementStatus =>
  v === "draft" || v === "published" || v === "archived"

export default async function AdminAnnouncementsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  await requirePermission(Permissions.ANNOUNCEMENT_MANAGE)
  const sp = await searchParams
  const statusParam = getSearchParam(sp, "status")
  const status = isValidStatus(statusParam) ? statusParam : undefined

  const [announcements, grades, classes] = await Promise.all([
    getAnnouncements({ status }),
    getGrades(),
    getAdminClasses(),
  ])

  return (
    <AdminAnnouncementsView
      announcements={announcements}
      grades={grades.map((g) => ({ id: g.id, name: g.name }))}
      classes={classes.map((c) => ({ id: c.id, name: c.name }))}
      initialStatus={status}
    />
  )
}
