import { NextResponse } from "next/server";
import db from "@/lib/db";
import bcrypt from "bcrypt";
import validate from "deep-email-validator";
import nodemailer from "nodemailer";
import crypto from "crypto";
import jwt from "jsonwebtoken";
import { getLogger } from "@/utils/logger";
import {EncodeUUID} from "@/utils/crypto/cryptography";


const logger = getLogger("api/user");

export async function POST(req: Request) {
  try {
    const { full_name, email, password } = await req.json();
    // logger.info("Credentials", {full_name: full_name, email: email, password: password, gender: gender, dob: dob});

    // //?-------------- CHECKING user username and mail nad passwod is exist or not----------------//
    const existingUser = await db.user.findFirst({
      where: {
        email: email.toLowerCase(),
      },
    })

    // //?-------------- If user email, username, or password exists then return error----------------//
    if (existingUser) {
      let message = " User with this ";
      if (existingUser.email === email) {
        message += "email exists";
      }

      logger.error(message, { email: email });

      return NextResponse.json(
        { user: null, message: message },
        { status: 404 }
      )
    }

    // //!-------------- If no user username and mail is exist ----------------//
    // //?----------- email valid or not checking-------------//
    const validationResult = await validate(email)

    if (!validationResult.valid) {
      logger.warn("Please validate email. Then try again ", { email: email, validationResult: validationResult.valid });

      return Response.json(
        {
          message: "Please validate email. Then try again",
        },
        { status: 404 }
      )
    }
    // //!-------- hash Password by bcrypt---------------//

    const salt = await bcrypt.genSalt(10);
    const hashPassword = await bcrypt.hash(password, salt);
    const idToken = jwt.sign(
      { email, full_name },
      process.env.NEXTAUTH_SECRET || "loveu2",
      {
        expiresIn: "1h",
      }
    );

    let newUser: any;
    try {
      newUser = await db.user.create({
        data: {
          email: email,
          password: hashPassword,
          profile: {
            create: {
              full_name: full_name.toString(),
              // date_of_birth: dob,
              // gender: gender,
            },
          },
          accounts: {
            create: {
              type: "credentials", // Default to "credentials"
              provider: "credentials", // Default to "credentials"
              providerAccountId: email, // Use email as provider account ID
              session_state: generateSessionState(),
              access_token: crypto.randomBytes(20).toString("hex"),
              refresh_token: crypto.randomBytes(20).toString("hex"),
              id_token: idToken,
              expires_at: Math.floor(Date.now() / 1000) + 3600, // 1 hour from now
            },
          },
        },
        include: {
          profile: {
            include: {
              address: true,
              picture: true,
            },
          },
          accounts: true,
        },
      });
    } catch (error: any) {
      logger.error("Prisma: Failed to create new user", { error: error });
      return NextResponse.json({ user: null, message: "Prisma: Failed to create new user" });
    }

    try {
      await sendEmail(email, newUser.uuid);
    } catch (error: any) {
      logger.error(" Error occurred when sending mail ", { errorData: error.config.data });
    }

    logger.info("User Created Successfully.", { email: email, userId: newUser.id })
    return NextResponse.json(
      {
        // user: newUser,
        message: "User Created Successfully ",
      },
      { status: 201 }
    );
  } catch (error: any) {
    logger.error(" User registration failed ", { errorMsg: error.message, errorData: error.config.data });
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}

// Function to generate session state
function generateSessionState(): string | undefined {
  return crypto.randomUUID().toString();
}

// Send Email using Nodemailer
async function sendEmail(email: string, newUserUUID: string) {
  try {

    // const salt = await bcrypt.genSalt(10);
    const hashedUserUUID = EncodeUUID(newUserUUID.toString())
    
    const hashedUserUUIDToken = jwt.sign(
      { hashedUserUUID },
      process.env.NEXTAUTH_SECRET || "loveu2",
      // {
      //   expiresIn: "5h",
      // }
    );


    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)
      },
    });



    const mailOptions = {
      from: `"Barrack Store" <${process.env.CPANEL_MAIL_FROM}>`,
      to: email,
      subject: "Welcome to Barrack E-Commerce",
      html: `<p>Hello,</p>
               <p>Thank you for choosing Barrack E-Commerce! We’re excited to have you on board.</p>
               <a href="${process.env.ROOTURl}/login/confirmemail/${hashedUserUUIDToken}"> Confirm you account</a>
               <p>If you need any assistance, feel free to reply to this email or contact our support team at ${process.env.GOOGLE_ACCOUNT_APP_GMAIL}.</p>
               <p>Happy shopping!</p>
               <p>Best regards,Barrack E-Commerce</p>`,
    };

    transporter.sendMail(mailOptions, (error, info) => {
      if (!error) {
        logger.info("Email has been sent successfully", { email: email });
      }
    });
  } catch (error: any) {
    logger.error("Error occurred when sending mail", { email: email, newUserUUID: newUserUUID, error: error.config.data });
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
