import { NextResponse } from "next/server";
import { hashPassword } from "@/lib/auth/password";
import { validateUsername, validatePassword } from "@/lib/auth/validation";
import { createUser, findByUsername } from "@/lib/db/repos/usersRepo";

export async function POST(request) {
  try {
    const body = await request.json();
    const { username, password } = body || {};

    const userCheck = validateUsername(username);
    if (!userCheck.valid) {
      return NextResponse.json({ error: userCheck.error }, { status: 400 });
    }

    const passCheck = validatePassword(password);
    if (!passCheck.valid) {
      return NextResponse.json({ error: passCheck.error }, { status: 400 });
    }

    const existing = await findByUsername(userCheck.value);
    if (existing) {
      return NextResponse.json({ error: "Username already taken" }, { status: 409 });
    }

    const passwordHash = hashPassword(password);
    const user = await createUser(userCheck.value, passwordHash);

    return NextResponse.json({
      message: "Registration submitted. Awaiting admin approval.",
      userId: user.id,
    }, { status: 201 });
  } catch (error) {
    console.error("[register] error:", error);
    return NextResponse.json({ error: "Registration failed" }, { status: 500 });
  }
}
