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

async function assertMemberOfPost(postId: string, familyId: string) {
  const rows = await sql.unsafe(
    `SELECT cm.role FROM circle_posts p
     JOIN circle_members cm ON cm.circle_id = p.circle_id AND cm.family_id = $2
     WHERE p.id = $1`,
    [postId, familyId]
  );
  return rows[0]?.role ?? null;
}

// GET — list comments for a post
export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string; postId: string }> }
) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

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

  if (!(await assertMemberOfPost(postId, familyId))) {
    return NextResponse.json({ error: "Not a member" }, { status: 403 });
  }

  const comments = await sql.unsafe(
    `SELECT c.id, c.author_family_id as "authorFamilyId", f.name as "authorFamilyName",
            c.body, c.created_at as "createdAt"
     FROM circle_post_comments c
     JOIN families f ON f.id = c.author_family_id
     WHERE c.post_id = $1
     ORDER BY c.created_at ASC`,
    [postId]
  );

  return NextResponse.json({ comments });
}

// POST — add a comment (members only; AI assistant not permitted here)
export async function POST(
  req: Request,
  { params }: { params: Promise<{ id: string; postId: string }> }
) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

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

  if (!(await assertMemberOfPost(postId, familyId))) {
    return NextResponse.json({ error: "Not a member" }, { status: 403 });
  }

  const { body } = await req.json();
  if (!body?.trim()) return NextResponse.json({ error: "Comment cannot be empty" }, { status: 400 });

  const [comment] = await sql.unsafe(
    `INSERT INTO circle_post_comments (post_id, author_family_id, body)
     VALUES ($1, $2, $3)
     RETURNING id, author_family_id as "authorFamilyId", body, created_at as "createdAt"`,
    [postId, familyId, body.trim()]
  );

  return NextResponse.json({ success: true, comment });
}
