import { TicketsPageClient } from "./tickets-page-client"
import { requireAuthenticatedSession } from "@/lib/auth-server"
import type { TicketFiltersState } from "@/lib/ticket-filters"
import type { TicketStatus } from "@/lib/schemas/ticket"

type TicketsSearchParams = Record<string, string | string[] | undefined>

export default async function TicketsPage({ searchParams }: { searchParams: Promise<TicketsSearchParams> }) {
  await requireAuthenticatedSession()
  const resolvedParams = await searchParams
  const initialFilters = deriveInitialFilters(resolvedParams ?? {})
  return <TicketsPageClient initialFilters={initialFilters} />
}

function getParamValue(value: string | string[] | undefined): string | undefined {
  if (Array.isArray(value)) {
    return value[0]
  }
  return value
}

function deriveInitialFilters(params: Record<string, string | string[] | undefined>): Partial<TicketFiltersState> {
  const initial: Partial<TicketFiltersState> = {}
  const isValidDateParam = (value?: string) => Boolean(value && /^\d{4}-\d{2}-\d{2}$/.test(value))
  const view = getParamValue(params.view)
  if (view === "completed" || view === "active") {
    initial.view = view
  }
  const status = getParamValue(params.status)
  if (status && ["PENDING", "AWAITING_ATTENDANCE", "PAUSED", "RESOLVED"].includes(status)) {
    initial.status = status as TicketStatus
  }
  const priority = getParamValue(params.priority)
  if (priority) initial.priority = priority
  const queue = getParamValue(params.queue)
  if (queue) initial.queue = queue
  const channel = getParamValue(params.channel)
  if (channel) initial.channel = channel
  const company = getParamValue(params.company)
  if (company) initial.company = company
  const assigneeId = getParamValue(params.assignee)
  if (assigneeId) initial.assigneeId = assigneeId
  const categoryId = getParamValue(params.category)
  if (categoryId) initial.categoryId = categoryId
  const from = getParamValue(params.from ?? params.dateFrom)
  if (isValidDateParam(from)) initial.dateFrom = from
  const to = getParamValue(params.to ?? params.dateTo)
  if (isValidDateParam(to)) initial.dateTo = to
  const sort = getParamValue(params.sort)
  if (sort === "recent" || sort === "oldest") {
    initial.sort = sort as TicketFiltersState["sort"]
  }
  const focus = getParamValue(params.focus)
  if (focus === "visits") {
    initial.focusVisits = true
  }
  return initial
}

