import { redirect } from "next/navigation"
import { getSessionUser } from "@/lib/session"
import { getAccountContext } from "@/lib/account"
import { listProviders, listConnections } from "@/lib/accounting"
import { AccountingIntegrations } from "@/components/dashboard/accounting-integrations"

export const metadata = { title: "Integrations" }
export const dynamic = "force-dynamic"

export default async function IntegrationsPage({
  searchParams,
}: {
  searchParams: Promise<{ connected?: string; error?: string }>
}) {
  const user = await getSessionUser()
  if (!user) redirect("/login")
  const ctx = await getAccountContext(user.id)
  const sp = await searchParams

  const providers = listProviders()
  const connections = ctx.isOwner ? await listConnections(ctx.ownerId) : []

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <div>
        <h2 className="text-lg font-bold text-white">Integrations</h2>
        <p className="text-sm text-white/40 mt-0.5">
          Connect your accounting software to automatically push rent income and expenses into your books.
        </p>
      </div>
      <AccountingIntegrations
        providers={providers}
        connections={connections}
        isOwner={ctx.isOwner}
        flash={{ connected: sp.connected, error: sp.error }}
      />
    </div>
  )
}
