import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { getDatabase } from "../../../../lib/database/index";
import log from "@/lib/logger";
import { userLoginSchema } from "@/lib/validation/schemas";
import {
  validateRequestBody,
  validationErrorResponse,
} from "@/lib/validation/helpers";
import {
  successResponse,
  unauthorizedResponse,
  internalErrorResponse,
} from "@/lib/api/responses";

export async function POST(request: NextRequest) {
  try {
    // Validate request body
    const validation = await validateRequestBody(request, userLoginSchema);

    if (!validation.success) {
      log.warn("Login validation failed", { errors: validation.errors });
      return validationErrorResponse(validation.errors);
    }

    const { email, password } = validation.data;

    const db = await getDatabase();
    const user = await db.getUserByEmail(email);

    if (!user) {
      return unauthorizedResponse("Invalid credentials");
    }

    const isValidPassword = await bcrypt.compare(password, user.password);

    if (!isValidPassword) {
      return unauthorizedResponse("Invalid credentials");
    }

    const { password: _, ...userWithoutPassword } = user;

    return successResponse({
      message: "Login successful",
      user: userWithoutPassword,
    });
  } catch (error) {
    log.error("Login failed", error);
    return internalErrorResponse();
  }
}
