import { NextRequest, NextResponse } from "next/server";
import dbConnect from "@/lib/mongodb";
import User from "@/models/User";
import UserType from "@/models/UserType";
import bcrypt from "bcryptjs";

async function getCustomerRoleId() {
  const role = await UserType.findOne({
    roleId: 2,
  }).select("_id");

  if (!role) {
    throw new Error("Customer role not found");
  }
  return role._id;
}

export async function POST(req: NextRequest) {
  try {
    await dbConnect();

    const body = await req.json();

    const name = body.name?.trim();
    const email = body.email?.trim()?.toLowerCase();
    const password = body.password?.trim();
    const phone = body.phone?.trim();

    // =========================
    // VALIDATION
    // =========================

    if (!name) {
      return NextResponse.json(
        {
          success: false,
          message: "Name is required",
        },
        { status: 400 }
      );
    }

    if (!email) {
      return NextResponse.json(
        {
          success: false,
          message: "Email is required",
        },
        { status: 400 }
      );
    }

    if (!password) {
      return NextResponse.json(
        {
          success: false,
          message: "Password is required",
        },
        { status: 400 }
      );
    }

    if (password.length < 6) {
      return NextResponse.json(
        {
          success: false,
          message: "Password must be at least 6 characters",
        },
        { status: 400 }
      );
    }

    // =========================
    // CHECK USER EXISTS
    // =========================

    const existingUser = await User.findOne({
      email,
    });

    if (existingUser) {
      return NextResponse.json(
        {
          success: false,
          message: "Email is already registered",
        },
        { status: 409 }
      );
    }

    // =========================
    // GET CUSTOMER ROLE
    // =========================

    const customerRoleId = await getCustomerRoleId();

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

const user = await User.create({
  name,
  email,
  password: hashedPassword,
  phone,
  role: customerRoleId,
  status: "active",
});

    return NextResponse.json(
      {
        success: true,
        message: "User registered successfully",
        data: {
          id: user._id,
          name: user.name,
          email: user.email,
          phone: user.phone,
          status: user.status,
          createdAt: user.createdAt,
        },
      },
      { status: 201 }
    );
  } catch (error: any) {
    console.error("Registration Error:", error);

    // Mongo duplicate key
    if (error?.code === 11000) {
      return NextResponse.json(
        {
          success: false,
          message: "Email already exists",
        },
        { status: 409 }
      );
    }

    return NextResponse.json(
      {
        success: false,
        message: error?.message || "Registration failed",
      },
      { status: 500 }
    );
  }
}