import { getBindings } from "@/lib/server/env";
import { getBookRepository } from "@/lib/server/app-services";

export async function GET(
  _request: Request,
  context: { params: Promise<{ bookId: string }> },
) {
  const { bookId } = await context.params;
  const book = await getBookRepository().get(bookId);
  if (!book) {
    return Response.json(
      { error: { code: "book_not_found", message: "找不到这本书。" } },
      { status: 404 },
    );
  }
  return Response.json({ book });
}

export async function PATCH(
  request: Request,
  context: { params: Promise<{ bookId: string }> },
) {
  try {
    const { bookId } = await context.params;
    const rawPayload: unknown = await request.json();
    if (!rawPayload || typeof rawPayload !== "object" || Array.isArray(rawPayload)) {
      throw new Error("请求内容必须是对象。");
    }
    const source = rawPayload as Record<string, unknown>;
    const payload: {
      title?: string;
      author?: string;
      preferredZhVoice?: string | null;
      preferredEnVoice?: string | null;
      preferredRate?: number | null;
    } = {};
    if (source.title !== undefined) {
      if (typeof source.title !== "string") throw new Error("书名格式不正确。");
      payload.title = source.title;
    }
    if (source.author !== undefined) {
      if (typeof source.author !== "string") throw new Error("作者格式不正确。");
      payload.author = source.author;
    }
    for (const key of ["preferredZhVoice", "preferredEnVoice"] as const) {
      const value = source[key];
      if (value !== undefined && value !== null && typeof value !== "string") {
        throw new Error("声音设置格式不正确。");
      }
      if (value !== undefined) payload[key] = value as string | null;
    }
    if (source.preferredRate !== undefined) {
      if (source.preferredRate !== null && typeof source.preferredRate !== "number") {
        throw new Error("语速格式不正确。");
      }
      payload.preferredRate = source.preferredRate as number | null;
    }
    return Response.json({
      book: await getBookRepository().updateMetadata(bookId, payload),
    });
  } catch (error) {
    return Response.json(
      {
        error: {
          code: "invalid_book_update",
          message: error instanceof Error ? error.message : "无法更新书籍。",
        },
      },
      { status: 400 },
    );
  }
}

export async function DELETE(
  request: Request,
  context: { params: Promise<{ bookId: string }> },
) {
  const confirmation = request.headers.get("x-confirm-delete");
  if (confirmation !== "DELETE") {
    return Response.json(
      { error: { code: "confirmation_required", message: "删除前必须明确确认。" } },
      { status: 428 },
    );
  }
  try {
    const { bookId } = await context.params;
    const objectKeys = await getBookRepository().delete(bookId);
    const { STORAGE } = getBindings();
    for (let index = 0; index < objectKeys.length; index += 1000) {
      await STORAGE.delete(objectKeys.slice(index, index + 1000));
    }
    return new Response(null, { status: 204 });
  } catch (error) {
    return Response.json(
      {
        error: {
          code: "delete_failed",
          message: error instanceof Error ? error.message : "删除失败。",
        },
      },
      { status: 404 },
    );
  }
}
