import { NextRequest, NextResponse } from "next/server";
import NewsLetter from "@/models/NewsLetter";
import { sendTemplateMail } from "@/lib/email";

import dbConnect from "@/lib/mongodb";

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

    const body = await req.json();

    const email = body.email?.trim()?.toLowerCase();

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

    // Check if email already exists
    const existingEntry = await NewsLetter.findOne({ email });

    if (existingEntry) {
      return NextResponse.json(
        {
          success: false,
          message: "This email is already subscribed to the newsletter",
        },
        { status: 409 }
      );
    }

    // Create new newsletter subscription
    const newSubscription = new NewsLetter({ email });
    await newSubscription.save();

    try {
      await sendTemplateMail({
        slug: "newletter",
        templateData: { email },
      });
    } catch (err: any) {
      console.error("Newsletter notification email failed", err);
    }

    return NextResponse.json({
      success: true,
      message: "Subscribed to newsletter successfully",
    });
  } catch (err: any) {
    return NextResponse.json(
      {
        success: false,
        error: err.message || "Failed to subscribe to newsletter",
      },
      { status: 500 }
    );
  }
}