import type { Metadata } from "next";
import { headers } from "next/headers";
import { eq } from "drizzle-orm";
import { resolveShareToken } from "@/modules/_core/share";
import { getEntityType } from "@/modules/_core/registry";
import { isRateLimited, recordFailure } from "@/lib/rate-limit";
import { db } from "@/lib/db";
import { users } from "@/modules/_core/schema";
import { ShareFrame } from "@/components/share/share-frame";

export const metadata: Metadata = {
  robots: { index: false, follow: false },
};

const RL_PREFIX_LEN = 8;

export default async function SharePage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = await params;
  const headersList = await headers();
  const ip =
    headersList.get("x-forwarded-for")?.split(",")[0]?.trim() ??
    headersList.get("x-real-ip") ??
    "0.0.0.0";
  const rlKey = `${ip}:${token.slice(0, RL_PREFIX_LEN)}`;

  if (isRateLimited(rlKey)) {
    return <ShareRateLimitError />;
  }

  const resolved = await resolveShareToken(token);
  if (!resolved) {
    recordFailure(rlKey);
    return <ShareError />;
  }

  const entityReg = getEntityType(resolved.entityType);
  if (!entityReg?.loadForShare || !entityReg.renderSharedView) {
    return <ShareError message="This content type cannot be shared." />;
  }

  const data = await entityReg.loadForShare(resolved.entityId);
  if (!data) {
    recordFailure(rlKey);
    return <ShareError />;
  }

  // Best-effort lookup of the creator's display name. Doesn't reveal email.
  const [creator] = resolved.createdBy
    ? await db
        .select({ name: users.name })
        .from(users)
        .where(eq(users.id, resolved.createdBy))
        .limit(1)
    : [];

  return (
    <ShareFrame
      expiresAt={resolved.expiresAt}
      capabilities={resolved.capabilities}
      token={token}
      sharedByName={creator?.name ?? null}
    >
      {entityReg.renderSharedView({ data, capabilities: resolved.capabilities, token })}
    </ShareFrame>
  );
}

function ShareRateLimitError() {
  return (
    <div className="flex min-h-[60vh] flex-col items-center justify-center gap-3 p-8 text-center">
      <h1 className="serif text-[28px] font-medium tracking-tight">Too many requests</h1>
      <p className="max-w-sm text-[13.5px] muted">
        You have made too many requests in a short period. Please wait a minute and try again.
      </p>
    </div>
  );
}

function ShareError({ message }: { message?: string }) {
  return (
    <div className="flex min-h-[60vh] flex-col items-center justify-center gap-3 p-8 text-center">
      <h1 className="serif text-[28px] font-medium tracking-tight">Link not found</h1>
      <p className="max-w-sm text-[13.5px] muted">
        {message ??
          "This share link may have expired or been revoked. Ask the sender for a new link."}
      </p>
    </div>
  );
}
