import { db } from "@/db/client";
import { books, words } from "@/db/schema";
import { requireAuth } from "@/lib/auth";
import BooksClient from "./BooksClient";
import { eq } from "drizzle-orm";

export const metadata = { title: "单词书管理" };

async function createBookAction(formData: FormData) {
  "use server";
  await requireAuth();
  const title = String(formData.get("title") || "").trim();
  const wordCount = Number(formData.get("wordCount") || 0);
  const coverUrl = String(formData.get("coverUrl") || "").trim() || null;
  const bookId = String(formData.get("bookId") || "").trim();
  const tags = String(formData.get("tags") || "").trim() || null;
  if (!title || !bookId || Number.isNaN(wordCount)) return;
  await db.insert(books).values({ title, wordCount, coverUrl, bookId, tags });
}

async function updateBookAction(formData: FormData) {
  "use server";
  await requireAuth();
  const id = Number(formData.get("id"));
  const title = String(formData.get("title") || "").trim();
  const wordCount = Number(formData.get("wordCount") || 0);
  const coverUrl = String(formData.get("coverUrl") || "").trim() || null;
  const bookId = String(formData.get("bookId") || "").trim();
  const tags = String(formData.get("tags") || "").trim() || null;
  if (!id || !title || !bookId || Number.isNaN(wordCount)) return;
  await db.update(books).set({ title, wordCount, coverUrl, bookId, tags }).where(eq(books.id, id));
}

async function deleteBookAction(formData: FormData) {
  "use server";
  await requireAuth();
  const id = Number(formData.get("id"));
  if (!id) return;
  // 获取 bookId 并在事务中删除关联 words 和 book 本身
  const row = (await db.select().from(books).where(eq(books.id, id)).limit(1))[0];
  if (!row) return;
  await db.transaction(async (tx) => {
    if (row.bookId) {
      await tx.delete(words).where(eq(words.bookId, row.bookId));
    }
    await tx.delete(books).where(eq(books.id, id));
  });
}

export default async function BooksPage() {
  await requireAuth();
  const rows = await db.select().from(books).orderBy(books.id);
  return (
    <BooksClient books={rows as any} createAction={createBookAction} updateAction={updateBookAction} deleteAction={deleteBookAction} />
  );
}
