import { NextRequest, NextResponse } from "next/server";
import nodemailer from "nodemailer";
import db from "@/lib/db";
import { getLogger } from "@/utils/logger";
import { encryptUUID } from "@/utils/crypto/cryptography";

const logger = getLogger("api/mailConfirmation");

export async function POST(request: NextRequest) {
  try {
    const { email } = await request.json();

    const existingUser = await db.user.findUnique({
      where: { email },
    });

    if (!existingUser) {
      logger.warn("No user found with this email", { email });
      return NextResponse.json({ message: "Not found" }, { status: 404 });
    }

    const transporter = nodemailer.createTransport({
      host: process.env.CPANEL_MAIL,
      port: 465,
      secure: true,
      auth: {
        user: process.env.CPANEL_USERNAME,
        pass: process.env.CPANEL_MAIL_PASSWORD,
      },
      tls: {
        rejectUnauthorized: false, // for local testing (self-signed certs)
      },
    });

    await transporter.verify().then(() => {
      console.log("SMTP server is ready to take messages");
    }).catch((err) => {
      console.error("SMTP connection failed:", err.message);
    });


    const token = encryptUUID(existingUser.uuid)

    const resetLink = `${process.env.ROOTURl}/login/resetPassword/${token}`


    const mailOptions = {
      from: `"Barrack Store" <${process.env.CPANEL_MAIL_FROM}>`,
      to: email,
      subject: "Reset your Barrack Store password",
      html: `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8" />
        <title>Password Reset</title>
      </head>
      <body style="margin:0;padding:0;background:#f4f6f9;font-family:Arial,Helvetica,sans-serif;">
        <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f9;padding:40px 0;">
          <tr>
            <td align="center">

              <table width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,.08);">

                <!-- Header -->
                <tr>
                  <td style="background:#111827;padding:35px;text-align:center;">
                    <h1 style="color:#ffffff;margin:0;font-size:28px;">
                      Barrack Store
                    </h1>
                    <p style="margin-top:10px;color:#d1d5db;font-size:15px;">
                      Secure Password Reset
                    </p>
                  </td>
                </tr>

                <!-- Content -->
                <tr>
                  <td style="padding:40px;">

                    <h2 style="margin-top:0;color:#111827;">
                      Hello,
                    </h2>

                    <p style="font-size:16px;color:#4b5563;line-height:1.8;">
                      We received a request to reset the password for your
                      <strong>Barrack Store</strong> account associated with:
                    </p>

                    <p style="font-size:18px;font-weight:bold;color:#111827;">
                      ${email}
                    </p>

                    <p style="font-size:16px;color:#4b5563;line-height:1.8;">
                      Click the button below to create a new password.
                    </p>

                    <table cellpadding="0" cellspacing="0" align="center" style="margin:35px auto;">
                      <tr>
                        <td align="center">
                          <a href="${resetLink}"
                            style="
                              background:#2563eb;
                              color:#ffffff;
                              text-decoration:none;
                              padding:16px 34px;
                              border-radius:8px;
                              display:inline-block;
                              font-size:16px;
                              font-weight:bold;
                            ">
                            Reset Password
                          </a>
                        </td>
                      </tr>
                    </table>

                    <p style="font-size:15px;color:#6b7280;line-height:1.8;">
                      If the button above doesn't work, copy and paste this link into
                      your browser:
                    </p>

                    <p style="word-break:break-all;font-size:14px;color:#2563eb;">
                      ${resetLink}
                    </p>

                    <hr style="border:none;border-top:1px solid #e5e7eb;margin:35px 0;">

                    <div style="background:#fff7ed;border-left:5px solid #f59e0b;padding:18px;border-radius:6px;">
                      <strong style="color:#92400e;">Security Notice</strong>
                      <p style="margin:10px 0 0;color:#92400e;font-size:15px;line-height:1.7;">
                        If you did not request a password reset, you can safely ignore this email.
                        Your password will remain unchanged.
                      </p>
                    </div>

                  </td>
                </tr>

                <!-- Footer -->
                <tr>
                  <td style="background:#f9fafb;padding:30px;text-align:center;border-top:1px solid #e5e7eb;">

                    <p style="margin:0;font-size:15px;color:#374151;font-weight:bold;">
                      Barrack Store Team
                    </p>

                    <p style="margin:12px 0 0;color:#6b7280;font-size:13px;">
                      This is an automated email. Please do not reply.
                    </p>

                    <p style="margin-top:18px;color:#9ca3af;font-size:12px;">
                      © ${new Date().getFullYear()} Barrack Store. All rights reserved.
                    </p>

                  </td>
                </tr>

              </table>

            </td>
          </tr>
        </table>
      </body>
      </html>
  `,
    };

    const info = await transporter.sendMail(mailOptions);
    logger.info("Email sent successfully to reset the password!", { response: info.response });

    return NextResponse.json({ message: "Email sent successfully to reset the password!" });

  } catch (error: any) {
    logger.error("Error occurred while sending mail", { message: error.message });
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
