import { NextResponse } from "next/server";
import { isAdminIdentity } from "@/lib/auth/admin";
import { createSessionToken, setSessionCookie } from "@/lib/auth/session";
import { verifyPassword } from "@/lib/auth/password";
import { issueEmailVerificationToken, sendEmailVerificationLink } from "@/lib/auth/verification";
import { prisma } from "@/lib/prisma";
import { buildAppUrl } from "@/lib/http/url";

function redirectTo(request: Request, path: string, params: Record<string, string>) {
  return NextResponse.redirect(buildAppUrl(request, path, params));
}

export async function POST(request: Request) {
  const formData = await request.formData();

  const email = typeof formData.get("email") === "string" ? formData.get("email")!.toString().trim().toLowerCase() : "";
  const password = typeof formData.get("password") === "string" ? formData.get("password")!.toString() : "";

  if (!email || !password) {
    return redirectTo(request, "/login", { error: "invalid_credentials" });
  }

  try {
    const user = await prisma.user.findUnique({ where: { email } });

    if (!user) {
      return redirectTo(request, "/login", { error: "invalid_credentials" });
    }

    const passwordMatches = await verifyPassword(password, user.passwordHash);

    if (!passwordMatches) {
      return redirectTo(request, "/login", { error: "invalid_credentials" });
    }

    if (!user.emailVerifiedAt) {
      const { token } = await issueEmailVerificationToken(user.id);
      const sendResult = await sendEmailVerificationLink(request, email, token);

      const verifyParams: Record<string, string> = {
        email,
        sent: sendResult.sent ? "1" : "0",
        unverified: "1",
      };

      if (!sendResult.sent) {
        verifyParams.error = "email_delivery_failed";
      }

      return redirectTo(request, "/verify", verifyParams);
    }

    let onboardingCompleted = false;

    try {
      const organization = await prisma.organization.findUnique({
        where: { userId: user.id },
        select: { onboardingCompletedAt: true },
      });

      onboardingCompleted = Boolean(organization?.onboardingCompletedAt);
    } catch {
      // Backward compatibility for databases that have not applied onboarding v2 migration yet.
      const legacyOrganization = await prisma.organization.findUnique({
        where: { userId: user.id },
        select: { id: true },
      });

      onboardingCompleted = Boolean(legacyOrganization);
    }

    const targetPath = isAdminIdentity(user.email, user.role)
      ? "/admin"
      : onboardingCompleted
        ? "/dashboard"
        : "/onboarding";

    const response = NextResponse.redirect(buildAppUrl(request, targetPath));
    const token = createSessionToken(user.id, user.email);

    setSessionCookie(response, token);

    return response;
  } catch {
    return redirectTo(request, "/login", { error: "server_error" });
  }
}
