// src/app/api/auth/resend-otp/route.ts
import prisma from "@/lib/prisma";

import { NextResponse } from "next/server";
import { randomOTP } from "../_lib/randomOTP";

export async function POST(req: Request) {
  try {
    const { nomor } = await req.json();

    if (!nomor || typeof nomor !== 'string') {
      return NextResponse.json(
        { success: false, message: "Nomor tidak valid" },
        { status: 400 }
      );
    }

    const codeOtp = randomOTP();
    const otpNumber = Number(codeOtp);
    console.log(`🔑 DEBUG RESEND OTP [${nomor}]: ${codeOtp}`);

    // Kirim OTP via WhatsApp
    const waMessage = `Website Desa Darmasaba - Kode ini bersifat RAHASIA dan JANGAN DI BAGIKAN KEPADA SIAPAPUN, termasuk anggota ataupun Admin lainnya.\n\n>> Kode OTP anda: ${codeOtp}.`;
    const waUrl = `https://wa.wibudev.com/code?nom=${encodeURIComponent(nomor)}&text=${encodeURIComponent(waMessage)}`;
    
    try {
      const waRes = await fetch(waUrl);
      if (!waRes.ok) {
        console.warn(`⚠️ WA Service HTTP Error (Resend): ${waRes.status} ${waRes.statusText}. Continuing since OTP is logged.`);
      } else {
        const waData = await waRes.json();
        console.log("📱 WA Response (Resend):", waData);
      }
    } catch (waError: unknown) {
      const errorMessage = waError instanceof Error ? waError.message : String(waError);
      console.warn("⚠️ WA Connection Exception (Resend). Continuing since OTP is logged.", errorMessage);
    }

    // Simpan OTP ke database
    const otpRecord = await prisma.kodeOtp.create({
      data: {
        nomor,
        otp: otpNumber,
        isActive: true,
      },
    });

    return NextResponse.json({
      success: true,
      message: "OTP baru dikirim",
      kodeId: otpRecord.id,
    });

  } catch (error) {
    console.error("Error Resend OTP:", error);
    return NextResponse.json(
      { success: false, message: "Gagal mengirim ulang OTP" },
      { status: 500 }
    );
  } finally {
    await prisma.$disconnect();
  }
}