import { NextRequest, NextResponse } from "next/server";
import { signIn } from "@/lib/auth";

interface SignInBody {
  email: string;
  password: string;
}

export async function POST(req: NextRequest) {
  let body: SignInBody;
  try {
    body = await req.json();
  } catch (err) {
    return NextResponse.json({ error: "Invalid request body." }, { status: 400 });
  }

  const email = body?.email;
  const password = body?.password;

  if (!email || !password) {
    return NextResponse.json(
      { error: "MissingCredentials", message: "Email and password are required." },
      { status: 400 }
    );
  }

  try {
    const result = await signIn.email({
      email,
      password,
    });

    console.log("[sign-in] signIn.email result:", JSON.stringify(result));

    if (result.error) {
      console.log("[sign-in] sign-in error:", result.error);
      return NextResponse.json(
        { error: result.error.code ?? "SignInFailed", message: result.error.message ?? "Invalid email or password." },
        { status: 401 }
      );
    }

    console.log("[sign-in] sign-in success, session should be set");
    return NextResponse.json({ success: true });
  } catch (err) {
    console.error("[sign-in] Unexpected error:", err);
    return NextResponse.json(
      { error: "ServiceError", message: "An unexpected error occurred." },
      { status: 500 }
    );
  }
}
