import { redirect } from "next/navigation"
import Link from "next/link"
import { desc, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { webhook_endpoints } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { getEffectiveOwnerId } from "@/lib/account"
import { WebhookManager } from "@/components/dashboard/webhook-manager"
import type { WebhookEndpointDTO } from "@/app/actions/webhooks"

export const metadata = { title: "Webhooks" }

export default async function WebhooksSettingsPage() {
  const user = await getSessionUser()
  if (!user) redirect("/login")

  // Endpoints belong to the account owner (team-aware) so every portfolio event
  // is delivered regardless of which member triggered it.
  const ownerId = await getEffectiveOwnerId(user.id)

  const rows = await db
    .select()
    .from(webhook_endpoints)
    .where(eq(webhook_endpoints.user_id, ownerId))
    .orderBy(desc(webhook_endpoints.created_at))

  const endpoints: WebhookEndpointDTO[] = rows.map((row) => ({
    id: row.id,
    url: row.url,
    description: row.description,
    events: row.events,
    secret: row.secret,
    status: row.status,
    source: row.source,
    last_success_at: row.last_success_at,
    last_error_at: row.last_error_at,
    last_error: row.last_error,
    failure_count: row.failure_count,
    created_at: row.created_at,
  }))

  return (
    <div className="max-w-2xl space-y-6">
      <div>
        <h2 className="text-lg font-semibold text-white">Webhooks</h2>
        <p className="text-sm text-white/40">
          Send real-time events to Zapier, Make, or your own server. Each delivery is signed with the
          endpoint&apos;s secret so you can verify it&apos;s from us. See the{" "}
          <Link
            href="/api-docs#webhooks"
            className="text-indigo-400 underline underline-offset-2 transition hover:text-indigo-300"
          >
            webhook documentation
          </Link>{" "}
          for the payload format and signature scheme.
        </p>
      </div>
      <WebhookManager initialEndpoints={endpoints} />
    </div>
  )
}
