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 },
    });

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

    // Generate OTP
    const code = Math.floor(1000 + Math.random() * 9000);
    const message = `Desa+\nMasukkan kode ini ${code} pada web app Desa+ anda. Jangan berikan pada siapapun.`;

    // Send WhatsApp
    try {
      const resWa = await fetch(`${process.env.URL_OTP}/api/wa/send-text`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${process.env.WA_SERVER_TOKEN}`,
        },
        body: JSON.stringify({
          number: user.phone,
          text: message,
        }),
      });

      if (!resWa.ok) {
        console.error("WhatsApp API Error:", resWa.status);
      }
    } catch (error) {
      console.error("WhatsApp Fetch Error:", error);
    }

    return Response.json({
      success: true,
      message: "Sukses",
      phone: user.phone,
      isWithoutOTP: user.isWithoutOTP,
      id: user.id,
      otp: code, // Return OTP for client-side verification (as per existing logic)
    });

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