import { prisma } from "@/module/_global";
import { ILogin } from "@/types";
import { NextRequest } from "next/server";

export async function POST(req: NextRequest) {
  try {
    const { phone }: ILogin = await req.json();
    const user = await prisma.user.findUnique({
      where: { phone, isActive: true },
      select: { id: true, phone: true, isWithoutOTP: true, Village: { select: { isActive: true } } },
    });

    if (!user) {
      return Response.json({
        success: false,
        message: "Nomor telepon tidak terdaftar",
      });
    }

    if (!user.Village?.isActive) {
      return Response.json({
        success: false,
        message: "Akun anda tidak aktif, silahkan hubungi admin",
      });
    }

    return Response.json({
      success: true,
      message: "Sukses",
      phone: user.phone,
      isWithoutOTP: user.isWithoutOTP,
      id: user.id,
    });

  } catch (error) {
    console.error(error);
    return Response.json({ message: "Internal Server Error (error: 500)", success: false });
  }
}
