import { apiError, requireOwner } from "@/lib/auth";
import { ensureSchema, rawDb } from "@/lib/db";

export async function PATCH(request: Request, context: { params: Promise<{ id: string }> }) {
  try {
    const ownerId = requireOwner(request);
    const { id } = await context.params;
    const body = await request.json() as { name?: string; description?: string };
    const name = body.name?.trim();
    if (!name) throw new Error("브랜드 이름을 입력해주세요.");
    await ensureSchema();
    const result = await rawDb().prepare("UPDATE brands SET name = ?, description = ?, updated_at = ? WHERE id = ? AND owner_id = ?")
      .bind(name.slice(0, 60), body.description?.trim().slice(0, 500) || "", Date.now(), id, ownerId).run();
    if (!result.meta.changes) throw new Error("브랜드를 찾을 수 없습니다.");
    return Response.json({ ok: true });
  } catch (error) { return apiError(error); }
}

export async function DELETE(request: Request, context: { params: Promise<{ id: string }> }) {
  try {
    const ownerId = requireOwner(request);
    const { id } = await context.params;
    await ensureSchema();
    const count = await rawDb().prepare("SELECT COUNT(*) AS count FROM brands WHERE owner_id = ?").bind(ownerId).first<{ count: number }>();
    if (!count || count.count <= 1) throw new Error("브랜드는 최소 1개가 필요합니다.");
    const result = await rawDb().prepare("DELETE FROM brands WHERE id = ? AND owner_id = ?").bind(id, ownerId).run();
    if (!result.meta.changes) throw new Error("브랜드를 찾을 수 없습니다.");
    return Response.json({ ok: true });
  } catch (error) { return apiError(error); }
}
