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 { getAdminAnnouncementsPageData } from "@/modules/announcements/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 getAdminAnnouncementsPageData(status)

  return (
    <AdminAnnouncementsView
      announcements={announcements}
      grades={grades}
      classes={classes}
      initialStatus={status}
    />
  )
}
