import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { getDatabase } from "../../../../lib/database/index";
import log from "@/lib/logger";
import { userSchema } from "@/lib/validation/schemas";
import {
  validateRequestBody,
  validationErrorResponse,
} from "@/lib/validation/helpers";

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

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

    const { email, password, firstName, lastName, phone } = validation.data;

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

    if (existingUser) {
      return NextResponse.json(
        { error: "User already exists" },
        { status: 409 },
      );
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    const newUser = await db.createUser({
      email,
      firstName,
      lastName,
      password: hashedPassword,
      phone,
      role: "client",
    });

    const newClient = await db.createClient({
      userId: newUser.id,
      membershipType: "basic",
      membershipStatus: "active",
      joinDate: new Date(),
    });

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

    return NextResponse.json(
      {
        message: "User registered successfully",
        user: { ...userWithoutPassword, client: newClient },
      },
      { status: 201 },
    );
  } catch (error) {
    log.error("User registration failed", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function GET() {
  try {
    const db = await getDatabase();
    const allUsers = await db.getAllUsers();
    const usersWithoutPassword = allUsers.map(
      ({ password: _, ...user }) => user,
    );
    return NextResponse.json({ users: usersWithoutPassword });
  } catch (error) {
    log.error("Failed to get users", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
