import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { verifyPassword } from "@/lib/auth/password";
import { userHasBoundThreadsAccount } from "@/lib/auth/accounts";
import { createSession } from "@/lib/auth/session";
import { apiRouteErrorResponse } from "@/lib/auth/api";

export async function POST(request: Request) {
  try {
    const body = (await request.json().catch(() => ({}))) as { email?: string; password?: string };
    const email = body.email?.trim().toLowerCase();
    const password = body.password ?? "";

    if (!email || !password) {
      return NextResponse.json({ error: "請輸入 Email 與密碼" }, { status: 400 });
    }

    const user = await prisma.user.findUnique({ where: { email } });
    if (!user || !verifyPassword(password, user.passwordHash)) {
      return NextResponse.json({ error: "Email 或密碼錯誤" }, { status: 401 });
    }

    await createSession(user.id);
    const needsThreadsBind = !(await userHasBoundThreadsAccount(user.id));

    return NextResponse.json({
      user: { id: user.id, email: user.email, name: user.name },
      needsThreadsBind,
    });
  } catch (error) {
    return apiRouteErrorResponse(error, "auth/login");
  }
}