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

interface ResetPasswordBody {
  password: string;
}

export async function POST(req: NextRequest) {
  let body: ResetPasswordBody;

  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid request body." }, { status: 400 });
  }

  const { password } = body;

  if (!password || password.length < 8) {
    return NextResponse.json(
      { error: "Password must be at least 8 characters." },
      { status: 400 }
    );
  }

  try {
    const result = await resetPassword({
      newPassword: password,
    });

    if (result.error) {
      console.error("[auth/reset-password] Reset failed:", result.error);
      return NextResponse.json(
        {
          error: result.error.code ?? "ResetFailed",
          message: result.error.message ?? "Failed to reset password. The link may have expired.",
        },
        { status: 400 }
      );
    }

    console.log("[auth/reset-password] Password reset successful");
    return NextResponse.json({ success: true });
  } catch (err) {
    console.error("[auth/reset-password] Unexpected error:", err);
    return NextResponse.json(
      { error: "InternalError", message: "An unexpected error occurred." },
      { status: 500 }
    );
  }
}
