import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { db } from "@/lib/db";
import { sendLoginCode } from "@/lib/ippanel";

const IRAN_MOBILE_REGEX = /^(\+98|98|0)?9\d{9}$/;

function normalizeIranMobile(phone: string) {
  const digits = phone.replace(/[^\d+]/g, "");
  if (!IRAN_MOBILE_REGEX.test(digits)) return null;

  if (digits.startsWith("+98")) return `0${digits.slice(3)}`;
  if (digits.startsWith("98")) return `0${digits.slice(2)}`;
  if (digits.startsWith("9")) return `0${digits}`;
  return digits;
}

function generateOtpCode() {
  return Math.floor(100000 + Math.random() * 900000).toString();
}

export async function POST(req: NextRequest) {
  const { phone } = await req.json().catch(() => ({}));
  const normalizedPhone = typeof phone === "string" ? normalizeIranMobile(phone) : null;

  if (!normalizedPhone) {
    return NextResponse.json({ error: "شماره موبایل معتبر نیست" }, { status: 400 });
  }

  const recentOtp = await db.loginOtp.findFirst({
    where: {
      phone: normalizedPhone,
      consumedAt: null,
      createdAt: { gte: new Date(Date.now() - 60 * 1000) },
    },
    orderBy: { createdAt: "desc" },
  });

  if (recentOtp) {
    return NextResponse.json(
      { error: "برای ارسال کد جدید حداقل ۶۰ ثانیه صبر کنید" },
      { status: 429 },
    );
  }

  const code = generateOtpCode();
  const codeHash = await bcrypt.hash(code, 10);

  await db.loginOtp.create({
    data: {
      phone: normalizedPhone,
      codeHash,
      expiresAt: new Date(Date.now() + 2 * 60 * 1000),
    },
  });

  try {
    await sendLoginCode(normalizedPhone, code);
  } catch (error) {
    console.error("IPPANEL send failed", error);
    return NextResponse.json({ error: "ارسال پیامک ناموفق بود" }, { status: 502 });
  }

  return NextResponse.json({
    ok: true,
    expiresIn: 120,
  });
}
