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

const ALLOWED_EMOJIS = ["❤️", "😂", "👍", "🙏", "😮", "😢"];

async function assertMemberOfPost(postId: string, familyId: string) {
  const rows = await sql.unsafe(
    `SELECT 1 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.length > 0;
}

// POST — toggle reaction (composite PK prevents duplicates)
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 { emoji } = await req.json();
  if (!ALLOWED_EMOJIS.includes(emoji)) {
    return NextResponse.json({ error: "Emoji not allowed" }, { status: 400 });
  }

  // Toggle: insert if not exists, delete if exists
  const existing = await sql.unsafe(
    `SELECT 1 FROM circle_post_reactions WHERE post_id = $1 AND family_id = $2 AND emoji = $3`,
    [postId, familyId, emoji]
  );

  if (existing.length > 0) {
    await sql.unsafe(
      `DELETE FROM circle_post_reactions WHERE post_id = $1 AND family_id = $2 AND emoji = $3`,
      [postId, familyId, emoji]
    );
    return NextResponse.json({ success: true, action: "removed" });
  }

  await sql.unsafe(
    `INSERT INTO circle_post_reactions (post_id, family_id, emoji) VALUES ($1, $2, $3)
     ON CONFLICT DO NOTHING`,
    [postId, familyId, emoji]
  );
  return NextResponse.json({ success: true, action: "added" });
}
