import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily } from "@/lib/auth";

// POST — validate invite token and add family as a member
export async function POST(
  _req: Request,
  { params }: { params: Promise<{ token: string }> }
) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const { token } = await params;

  // Validate token server-side — never trust client-supplied circleId
  const [invite] = await sql.unsafe(
    `SELECT id, circle_id as "circleId", expires_at as "expiresAt", consumed_at as "consumedAt"
     FROM circle_invites WHERE token = $1`,
    [token]
  );

  if (!invite)                         return NextResponse.json({ error: "Invalid invite link" },      { status: 404 });
  if (invite.consumedAt)               return NextResponse.json({ error: "This invite has already been used" }, { status: 409 });
  if (new Date(invite.expiresAt) < new Date()) return NextResponse.json({ error: "This invite has expired" }, { status: 410 });

  // Idempotent — already a member
  const existing = await sql.unsafe(
    `SELECT 1 FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
    [invite.circleId, familyId]
  );
  if (existing.length > 0) {
    return NextResponse.json({ error: "You are already a member of this circle" }, { status: 409 });
  }

  // Add member + consume invite atomically
  await sql.unsafe(
    `INSERT INTO circle_members (circle_id, family_id, role) VALUES ($1, $2, 'member')`,
    [invite.circleId, familyId]
  );
  await sql.unsafe(
    `UPDATE circle_invites SET consumed_at = now() WHERE id = $1`,
    [invite.id]
  );

  const [circle] = await sql.unsafe(
    `SELECT id, name FROM circles WHERE id = $1`,
    [invite.circleId]
  );

  return NextResponse.json({ success: true, circleId: invite.circleId, circleName: circle?.name });
}

// GET — preview the circle behind a token (name, member count) without joining
export async function GET(
  _req: Request,
  { params }: { params: Promise<{ token: string }> }
) {
  const { token } = await params;

  const [invite] = await sql.unsafe(
    `SELECT ci.id, ci.circle_id as "circleId", ci.expires_at as "expiresAt",
            ci.consumed_at as "consumedAt", c.name as "circleName",
            (SELECT COUNT(*) FROM circle_members WHERE circle_id = c.id)::int as "memberCount"
     FROM circle_invites ci
     JOIN circles c ON c.id = ci.circle_id
     WHERE ci.token = $1`,
    [token]
  );

  if (!invite)               return NextResponse.json({ error: "Invalid invite link" },             { status: 404 });
  if (invite.consumedAt)     return NextResponse.json({ error: "This invite has already been used" }, { status: 409 });
  if (new Date(invite.expiresAt) < new Date()) return NextResponse.json({ error: "This invite has expired" }, { status: 410 });

  return NextResponse.json({
    circleName: invite.circleName,
    memberCount: invite.memberCount,
    expiresAt: invite.expiresAt,
  });
}
