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

function getR2Config() {
  return {
    accountId: process.env.R2_ACCOUNT_ID,
    accessKeyId: process.env.R2_ACCESS_KEY_ID,
    secretKey: process.env.R2_SECRET_ACCESS_KEY,
    bucket: process.env.R2_BUCKET_NAME,
    publicUrl: process.env.R2_PUBLIC_URL,
  };
}

// PATCH /api/memories/[id] — update title, description, isPrivate, takenAt
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const body = await req.json();
  const { title, description, isPrivate, takenAt } = body;

  // Verify ownership
  const existing = await sql`SELECT id, is_private FROM memories WHERE id = ${id} AND family_id = ${familyId} LIMIT 1`;
  if (!existing[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });

  // If marking private, wipe vision data
  const wasPrivate = existing[0].is_private;
  const nowPrivate = isPrivate !== undefined ? isPrivate : wasPrivate;
  const wipeVision = !wasPrivate && nowPrivate;

  if (wipeVision) {
    await sql`
      UPDATE memories SET
        title = COALESCE(${title ?? null}, title),
        description = COALESCE(${description ?? null}, description),
        taken_at = COALESCE(${takenAt ?? null}, taken_at),
        is_private = ${nowPrivate},
        vision_caption = NULL,
        vision_tags = NULL,
        vision_embedding = NULL,
        updated_at = now()
      WHERE id = ${id} AND family_id = ${familyId}
    `;
  } else {
    await sql`
      UPDATE memories SET
        title = COALESCE(${title ?? null}, title),
        description = COALESCE(${description ?? null}, description),
        taken_at = COALESCE(${takenAt ?? null}, taken_at),
        is_private = ${nowPrivate},
        updated_at = now()
      WHERE id = ${id} AND family_id = ${familyId}
    `;
  }

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

// DELETE /api/memories/[id]
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const rows = await sql`SELECT r2_key, r2_thumbnail_key FROM memories WHERE id = ${id} AND family_id = ${familyId} LIMIT 1`;
  if (!rows[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const R2 = getR2Config();
  if (R2.accountId && R2.accessKeyId && R2.secretKey && R2.bucket) {
    const client = new S3Client({
      region: "auto",
      endpoint: `https://${R2.accountId}.r2.cloudflarestorage.com`,
      credentials: { accessKeyId: R2.accessKeyId, secretAccessKey: R2.secretKey },
    });
    await client.send(new DeleteObjectCommand({ Bucket: R2.bucket, Key: rows[0].r2_key })).catch(() => {});
    if (rows[0].r2_thumbnail_key) {
      await client.send(new DeleteObjectCommand({ Bucket: R2.bucket, Key: rows[0].r2_thumbnail_key })).catch(() => {});
    }
  }

  await sql`DELETE FROM memories WHERE id = ${id} AND family_id = ${familyId}`;
  return NextResponse.json({ success: true });
}
