import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily } from "@/lib/auth";
import { S3Client, DeleteObjectCommand } from "@aws-sdk/client-s3";

// PATCH — author can edit the text body of their own post
export async function PATCH(
  req: Request,
  { params }: { params: Promise<{ id: string; postId: string }> }
) {
  try {
    const auth = await requireFamily();
    if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

    const familyId = auth.session!.familyId!;
    const { id: circleId, postId } = await params;

    const [post] = await sql.unsafe(
      `SELECT author_family_id as "authorFamilyId" FROM circle_posts WHERE id = $1 AND circle_id = $2`,
      [postId, circleId]
    );
    if (!post) return NextResponse.json({ error: "Post not found" }, { status: 404 });
    if (post.authorFamilyId !== familyId)
      return NextResponse.json({ error: "Only the author can edit this post" }, { status: 403 });

    const body = await req.json();
    const newBody = (body.body ?? "").trim();

    await sql.unsafe(`UPDATE circle_posts SET body = $1 WHERE id = $2`, [newBody || null, postId]);
    return NextResponse.json({ success: true });
  } catch (err: unknown) {
    return NextResponse.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });
  }
}

function makeR2Client() {
  return new S3Client({
    region: "auto",
    endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
    credentials: {
      accessKeyId:     process.env.R2_ACCESS_KEY_ID!,
      secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
    },
  });
}

// DELETE — author or circle admin can delete a post; deletes R2 copy too
export async function DELETE(
  _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 { id: circleId, postId } = await params;

  const [post] = await sql.unsafe(
    `SELECT p.id, p.author_family_id as "authorFamilyId", p.image_key as "imageKey"
     FROM circle_posts p WHERE p.id = $1 AND p.circle_id = $2`,
    [postId, circleId]
  );
  if (!post) return NextResponse.json({ error: "Post not found" }, { status: 404 });

  // Permission: own post OR admin of this circle
  const isAuthor = post.authorFamilyId === familyId;
  if (!isAuthor) {
    const [membership] = await sql.unsafe(
      `SELECT role FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
      [circleId, familyId]
    );
    if (membership?.role !== "admin") {
      return NextResponse.json({ error: "Not authorised to delete this post" }, { status: 403 });
    }
  }

  // Delete R2 image copy (circle-posts/{postId}/ prefix) — no orphans
  if (post.imageKey) {
    await makeR2Client().send(
      new DeleteObjectCommand({ Bucket: process.env.R2_BUCKET_NAME!, Key: post.imageKey })
    ).catch(() => {}); // don't fail the whole delete if R2 is flaky
  }

  // DB cascade removes comments, reactions, reports
  await sql.unsafe(`DELETE FROM circle_posts WHERE id = $1`, [postId]);

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