import { NextRequest, NextResponse } from "next/server";
import db from "@/lib/db";
import { OrderStatus, PaymentMethod, ShipmentStatus } from "@prisma/client";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import nodemailer from "nodemailer";
import { createPayment } from "@/utils/bkash/bkash";
import { getLogger } from "@/utils/logger";

const logger = getLogger('/api/checkout');

export async function POST(request: NextRequest) {
    try {
        const req = await request.formData()
        const session = await getServerSession(authOptions)
        if (!session) {
            return NextResponse.json({ mssg: "You are not authorized !" }, { status: 403 })
        }

        // console.log(req)

        const name = req.get("name")
        const email = req.get("email") as string | null
        const phone = req.get("phone")
        const rname = req.get("rname")
        const address_uuid = req.get("address_uuid")
        const delivery_cost = req.get("delivery_cost")
        const payment_method_str = req.get("payment_method");



        let payment_method: PaymentMethod;
        if (payment_method_str === 'Cash On Delivery') {
            payment_method = PaymentMethod.CASH_ON_DELIVERY;
        } else if (payment_method_str === 'BKASH') {
            payment_method = PaymentMethod.BKASH;
        } else if (payment_method_str === 'NAGAD') {
            payment_method = PaymentMethod.NAGAD;
        } else {
            payment_method = PaymentMethod.CASH_ON_DELIVERY;
        }

        // console.log(payment_method);


        const user = await db.user.findUnique({
            where: {
                uuid: session?.user.uuid
            },
            include: {
                profile: {
                    include: {
                        Cart: {
                            include: {
                                CartItem: {
                                    include: {
                                        variant: true
                                    }
                                }
                            }
                        }
                    }
                }
            }
        })

        const cart = user?.profile ? user.profile.Cart : null
        const address = await db.address.findUnique({
            where: {
                uuid: address_uuid as string
            }
        })

        var coupon = null
        if (cart?.discountCode) {
            coupon = await db.coupon.findUnique({
                where: { code: cart.discountCode }
            })

            await db.couponUsage.create({
                data: {
                    couponId: coupon?.id as number,
                    userId: user?.id as number,
                    usedAt: new Date()
                }
            })

        }



        const order = await db.orders.create({
            data: {
                applied_coupon: coupon ? { connect: { id: coupon.id } } : undefined,
                applied_discount: cart?.discountAmount ?? 0,
                order_status: OrderStatus.PROCESSING,
                order_total_amount: cart?.totalPrice ?? 0,
                address: { connect: { uuid: address_uuid as string } },
                delivery_cost: parseFloat(delivery_cost as string),
                profile: { connect: { uuid: user?.profile?.uuid ?? "" } },
                shipment_details: {
                    create: {
                        name: name as string,
                        email: email as string,
                        phone: phone as string,
                        receiver_name: rname as string,
                        shipment_status: ShipmentStatus.PENDING,
                        delivery_cost_id: address?.shipping_zone_id ?? 0,

                    }
                },
                payment: {
                    create: {

                        payment_status: "PENDING",
                        payment_method: payment_method,
                        amount: (cart?.totalPrice ?? 0) + parseFloat(delivery_cost as string),
                        profile: { connect: { uuid: user?.profile?.uuid ?? "" } },
                    }
                },

                order_items: {
                    create: cart?.CartItem.map((item) => ({
                        quantity: item.quantity,
                        variant: { connect: { uuid: item.variant.uuid } },
                        price: item.variant.special_price,
                    })) ?? []
                }

                // Add other required fields here
            }
        })

        await db.payments.update({
            where: {
                id: order.payment_id ?? undefined
            },
            data: {
                order: { connect: { id: order.id } }
            }
        });



        if (cart?.CartItem) {
            await Promise.all(
                cart.CartItem.map(async (item) => {
                    await db.productVariant.update({
                        where: {
                            id: item.variant.id
                        },
                        data: {
                            quantity: item.variant.quantity - item.quantity
                        }
                    });
                })
            );
        }

        await db.cart.delete({
            where: {
                uuid: cart?.uuid ?? ""
            }
        })

        const orderNumber = uuidToOrderNumber(order.id)

        const transporter = nodemailer.createTransport({
            host: "smtp.gmail.com",
            port: 587,
            secure: false,
            auth: {
                user: process.env.GOOGLE_ACCOUNT_APP_GMAIL,
                pass: process.env.GOOGLE_ACCOUNT_APP_PASSWORD,
            },
        });

        const recipients = [
                email,
                user?.email,
            ].filter((item): item is string => Boolean(item));

        const orderedProductsHtml = cart?.CartItem.map((item) => `
                <tr>
                    <td style="
                    padding:12px;
                    border-bottom:1px solid #e5e7eb;
                    color:#111827;
                    font-size:14px;
                    ">
                    ${item.variant.name ?? "Product"}
                    </td>

                    <td style="
                    padding:12px;
                    border-bottom:1px solid #e5e7eb;
                    text-align:center;
                    color:#374151;
                    font-size:14px;
                    ">
                    ${item.quantity}
                    </td>

                    <td style="
                    padding:12px;
                    border-bottom:1px solid #e5e7eb;
                    text-align:right;
                    color:#111827;
                    font-weight:600;
                    font-size:14px;
                    ">
                    ৳${item.variant.special_price}
                    </td>
                </tr>
                `).join("") ?? "";

        if (typeof email === "string" && email.length > 0 && recipients[0] != recipients[1]) {

            const receiverMailOptions = {
                from: `"Barrack Store" <${process.env.CPANEL_MAIL_FROM}>`,
                to: recipients[0],
                subject: "You are asked to receive an order",
                html: `
                    <!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset="UTF-8" />
                            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                            <title>Order Confirmation</title>
                        </head>

                        <body style="margin:0; padding:0; background-color:#f5f5f5; font-family:Arial, Helvetica, sans-serif;">
                            <table width="100%" cellpadding="0" cellspacing="0" style="padding:30px 0;">
                                <tr>
                                    <td align="center">

                                        <table width="600" cellpadding="0" cellspacing="0"
                                            style="background:#ffffff; border-radius:12px; overflow:hidden; box-shadow:0 4px 15px rgba(0,0,0,0.08);">

                                            <tr>
                                                <td style="background:#111827; padding:30px; text-align:center;">
                                                    <h1 style="margin:0; color:#ffffff; font-size:28px;">
                                                        Barrack Store
                                                    </h1>

                                                    <p style="margin:8px 0 0; color:#d1d5db; font-size:14px;">
                                                        Your trusted shopping destination
                                                    </p>
                                                </td>
                                            </tr>


                                            <tr>
                                                <td style="padding:35px 40px; color:#333333;">

                                                    <h2 style="margin:0 0 20px; color:#111827; font-size:22px;">
                                                        Hello ${rname},
                                                    </h2>


                                                    <p style="font-size:16px; line-height:1.6; margin:0 0 15px;">
                                                        ${user?.email} wants you to receive this order. 
                                                    </p>


                                                    <div style="
                                                        background:#f3f4f6;
                                                        border-radius:8px;
                                                        padding:20px;
                                                        margin:25px 0;
                                                    ">
                                                        <p style="margin:0 0 8px; font-size:14px; color:#6b7280;">
                                                            Order Tracking ID
                                                        </p>

                                                        <p style="
                                                            margin:0;
                                                            font-size:18px;
                                                            font-weight:bold;
                                                            color:#111827;
                                                        ">
                                                            ${orderNumber}
                                                        </p>
                                                    </div>



                                                    <h3 style="
                                                        margin:30px 0 15px;
                                                        color:#111827;
                                                        font-size:18px;
                                                    ">
                                                        Ordered Products
                                                    </h3>


                                                    <table width="100%" cellpadding="0" cellspacing="0"
                                                        style="
                                                            border-collapse:collapse;
                                                            border:1px solid #e5e7eb;
                                                            border-radius:8px;
                                                        ">

                                                        <thead>
                                                            <tr style="background:#f9fafb;">

                                                                <th style="
                                                                    padding:12px;
                                                                    text-align:left;
                                                                    font-size:13px;
                                                                    color:#6b7280;
                                                                ">
                                                                    Product
                                                                </th>

                                                                <th style="
                                                                    padding:12px;
                                                                    text-align:center;
                                                                    font-size:13px;
                                                                    color:#6b7280;
                                                                ">
                                                                    Quantity
                                                                </th>

                                                                <th style="
                                                                    padding:12px;
                                                                    text-align:right;
                                                                    font-size:13px;
                                                                    color:#6b7280;
                                                                ">
                                                                    Price
                                                                </th>

                                                            </tr>
                                                        </thead>


                                                        <tbody>
                                                            ${orderedProductsHtml}
                                                        </tbody>

                                                    </table>



                                                    <p style="
                                                        font-size:15px;
                                                        line-height:1.6;
                                                        color:#555;
                                                        margin-top:30px;
                                                    ">
                                                        You can use your tracking ID to check your order status.
                                                        We will notify you when your order moves to the next stage.
                                                    </p>


                                                    <p style="margin-top:30px; font-size:15px;">
                                                        Thank you for choosing 
                                                        <strong>Barrack Store</strong>.
                                                    </p>

                                                </td>
                                            </tr>



                                            <tr>
                                                <td style="
                                                    background:#f9fafb;
                                                    padding:20px;
                                                    text-align:center;
                                                    color:#6b7280;
                                                    font-size:13px;
                                                ">
                                                    © ${new Date().getFullYear()} Barrack Store. All rights reserved.
                                                </td>
                                            </tr>


                                        </table>

                                    </td>
                                </tr>
                            </table>
                        </body>
                        </html>
                    `,
            };
            
            
            
            transporter.sendMail(receiverMailOptions, (error, info) => {
                if (!error) {
                    console.log('Email has been sent to receiver', { response: info.response });
                    //   logger.info("Email has been sent ", {response: info.response});
                }
            })
            
        }

        const userMailOptions = {
                from: `"Barrack Store" <${process.env.CPANEL_MAIL_FROM}>`,
                to: recipients[1],
                subject: "Your order has been placed successfully",
                html: `
                    <!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset="UTF-8" />
                            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                            <title>Order Confirmation</title>
                        </head>

                        <body style="margin:0; padding:0; background-color:#f5f5f5; font-family:Arial, Helvetica, sans-serif;">
                            <table width="100%" cellpadding="0" cellspacing="0" style="padding:30px 0;">
                                <tr>
                                    <td align="center">

                                        <table width="600" cellpadding="0" cellspacing="0"
                                            style="background:#ffffff; border-radius:12px; overflow:hidden; box-shadow:0 4px 15px rgba(0,0,0,0.08);">

                                            <tr>
                                                <td style="background:#111827; padding:30px; text-align:center;">
                                                    <h1 style="margin:0; color:#ffffff; font-size:28px;">
                                                        Barrack Store
                                                    </h1>

                                                    <p style="margin:8px 0 0; color:#d1d5db; font-size:14px;">
                                                        Your trusted shopping destination
                                                    </p>
                                                </td>
                                            </tr>


                                            <tr>
                                                <td style="padding:35px 40px; color:#333333;">

                                                    <h2 style="margin:0 0 20px; color:#111827; font-size:22px;">
                                                        Hello ${user?.profile?.full_name},
                                                    </h2>

                                                    <p style="font-size:16px; line-height:1.6; margin:0 0 15px;">
                                                        Thank you for shopping with Barrack Store.
                                                        Your order has been placed successfully and we are preparing it for processing.
                                                    </p>


                                                    <div style="
                                                        background:#f3f4f6;
                                                        border-radius:8px;
                                                        padding:20px;
                                                        margin:25px 0;
                                                    ">
                                                        <p style="margin:0 0 8px; font-size:14px; color:#6b7280;">
                                                            Order Tracking ID
                                                        </p>

                                                        <p style="
                                                            margin:0;
                                                            font-size:18px;
                                                            font-weight:bold;
                                                            color:#111827;
                                                        ">
                                                            ${orderNumber}
                                                        </p>
                                                    </div>



                                                    <h3 style="
                                                        margin:30px 0 15px;
                                                        color:#111827;
                                                        font-size:18px;
                                                    ">
                                                        Ordered Products
                                                    </h3>


                                                    <table width="100%" cellpadding="0" cellspacing="0"
                                                        style="
                                                            border-collapse:collapse;
                                                            border:1px solid #e5e7eb;
                                                            border-radius:8px;
                                                        ">

                                                        <thead>
                                                            <tr style="background:#f9fafb;">

                                                                <th style="
                                                                    padding:12px;
                                                                    text-align:left;
                                                                    font-size:13px;
                                                                    color:#6b7280;
                                                                ">
                                                                    Product
                                                                </th>

                                                                <th style="
                                                                    padding:12px;
                                                                    text-align:center;
                                                                    font-size:13px;
                                                                    color:#6b7280;
                                                                ">
                                                                    Quantity
                                                                </th>

                                                                <th style="
                                                                    padding:12px;
                                                                    text-align:right;
                                                                    font-size:13px;
                                                                    color:#6b7280;
                                                                ">
                                                                    Price
                                                                </th>

                                                            </tr>
                                                        </thead>


                                                        <tbody>
                                                            ${orderedProductsHtml}
                                                        </tbody>

                                                    </table>



                                                    <p style="
                                                        font-size:15px;
                                                        line-height:1.6;
                                                        color:#555;
                                                        margin-top:30px;
                                                    ">
                                                        You can use your tracking ID to check your order status.
                                                        We will notify you when your order moves to the next stage.
                                                    </p>


                                                    <p style="margin-top:30px; font-size:15px;">
                                                        Thank you for choosing 
                                                        <strong>Barrack Store</strong>.
                                                    </p>

                                                </td>
                                            </tr>



                                            <tr>
                                                <td style="
                                                    background:#f9fafb;
                                                    padding:20px;
                                                    text-align:center;
                                                    color:#6b7280;
                                                    font-size:13px;
                                                ">
                                                    © ${new Date().getFullYear()} Barrack Store. All rights reserved.
                                                </td>
                                            </tr>


                                        </table>

                                    </td>
                                </tr>
                            </table>
                        </body>
                        </html>
                    `,
            };

        transporter.sendMail(userMailOptions, (error, info) => {
                if (!error) {
                    console.log('Email has been sent to user', { response: info.response });
                    //   logger.info("Email has been sent ", {response: info.response});
                }
            })

        const admins = await db.user.findMany({
                where: {
                    role: "ADMIN"
                },
                take: 10
            })

            admins.forEach((admin)=>{
                const adminMailOptions = {
                from: `"Barrack Store" <${process.env.CPANEL_MAIL_FROM}>`,
                to: admin.email,
                subject: "A Customer has placed an order successfully",
                html: `
                    <!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset="UTF-8" />
                            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                            <title>Order Confirmation</title>
                        </head>

                        <body style="margin:0; padding:0; background-color:#f5f5f5; font-family:Arial, Helvetica, sans-serif;">
                            <table width="100%" cellpadding="0" cellspacing="0" style="padding:30px 0;">
                                <tr>
                                    <td align="center">

                                        <table width="600" cellpadding="0" cellspacing="0"
                                            style="background:#ffffff; border-radius:12px; overflow:hidden; box-shadow:0 4px 15px rgba(0,0,0,0.08);">

                                            <tr>
                                                <td style="background:#111827; padding:30px; text-align:center;">
                                                    <h1 style="margin:0; color:#ffffff; font-size:28px;">
                                                        Barrack Store
                                                    </h1>

                                                    <p style="margin:8px 0 0; color:#d1d5db; font-size:14px;">
                                                        Your trusted shopping destination
                                                    </p>
                                                </td>
                                            </tr>


                                            <tr>
                                                <td style="padding:35px 40px; color:#333333;">

                                                    <h2 style="margin:0 0 20px; color:#111827; font-size:22px;">
                                                        Hello ${name} needs to receive an order which was placed by ${user?.profile?.full_name},
                                                    </h2>


                                                    <div style="
                                                        background:#f3f4f6;
                                                        border-radius:8px;
                                                        padding:20px;
                                                        margin:25px 0;
                                                    ">
                                                        <p style="margin:0 0 8px; font-size:14px; color:#6b7280;">
                                                            Order Tracking ID
                                                        </p>

                                                        <p style="
                                                            margin:0;
                                                            font-size:18px;
                                                            font-weight:bold;
                                                            color:#111827;
                                                        "> Order ID - 
                                                            ${order.id} 
                                                        </p>
                                                        <p style="
                                                            margin:0;
                                                            font-size:18px;
                                                            font-weight:bold;
                                                            color:#111827;
                                                        "> Order Number - 
                                                            ${orderNumber} 
                                                        </p>

                                                    </div>



                                                    <h3 style="
                                                        margin:30px 0 15px;
                                                        color:#111827;
                                                        font-size:18px;
                                                    ">
                                                        Ordered Products
                                                    </h3>


                                                    <table width="100%" cellpadding="0" cellspacing="0"
                                                        style="
                                                            border-collapse:collapse;
                                                            border:1px solid #e5e7eb;
                                                            border-radius:8px;
                                                        ">

                                                        <thead>
                                                            <tr style="background:#f9fafb;">

                                                                <th style="
                                                                    padding:12px;
                                                                    text-align:left;
                                                                    font-size:13px;
                                                                    color:#6b7280;
                                                                ">
                                                                    Product
                                                                </th>

                                                                <th style="
                                                                    padding:12px;
                                                                    text-align:center;
                                                                    font-size:13px;
                                                                    color:#6b7280;
                                                                ">
                                                                    Quantity
                                                                </th>

                                                                <th style="
                                                                    padding:12px;
                                                                    text-align:right;
                                                                    font-size:13px;
                                                                    color:#6b7280;
                                                                ">
                                                                    Price
                                                                </th>

                                                            </tr>
                                                        </thead>


                                                        <tbody>
                                                            ${orderedProductsHtml}
                                                        </tbody>

                                                    </table>



                                                    <p style="
                                                        font-size:15px;
                                                        line-height:1.6;
                                                        color:#555;
                                                        margin-top:30px;
                                                    ">
                                                        You can use your tracking ID to check your order status.
                                                        We will notify you when your order moves to the next stage.
                                                    </p>


                                                    <p style="margin-top:30px; font-size:15px;">
                                                        Thank you for choosing 
                                                        <strong>Barrack Store</strong>.
                                                    </p>

                                                </td>
                                            </tr>



                                            <tr>
                                                <td style="
                                                    background:#f9fafb;
                                                    padding:20px;
                                                    text-align:center;
                                                    color:#6b7280;
                                                    font-size:13px;
                                                ">
                                                    © ${new Date().getFullYear()} Barrack Store. All rights reserved.
                                                </td>
                                            </tr>


                                        </table>

                                    </td>
                                </tr>
                            </table>
                        </body>
                        </html>
                    `,
            };
                transporter.sendMail(adminMailOptions, (error, info) => {
                    console.log('Emails have been sent to admins', { response: info.response });
                })
            })
        

        if (payment_method == PaymentMethod.BKASH) {

            // Retrieve the payment object from the created order
            const payment = await db.payments.findUnique({
                where: {
                    id: order.payment_id ?? undefined
                }
            });

            const payment_response = await createPayment(
                (cart?.totalPrice ?? 0) + parseFloat(delivery_cost as string),
                (phone as string) ?? "",
                payment?.uuid as string
            );

            // console.log(payment_response.data)

            await db.payments.update({
                where: {
                    id: order.payment_id ?? undefined
                },
                data: {
                    paymentID: payment_response.data.paymentID,
                    transactionStatus: payment_response.data.transactionStatus,
                    payment_date: new Date(),
                }
            });

            return NextResponse.json({
                orderNumber: orderNumber, order, payment: payment_response.data,
                payment_url: payment_response.data.bkashURL
            }, { status: 201 });
        }

        return NextResponse.json({ orderNumber: orderNumber, order }, { status: 200 });


    }
    catch (error: any) {
        logger.error("Failed to place an order", {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        });
        // console.error("Error occurred when creating checkout session", { errorMsg: error.message, errorData: error.config.data });
        return new NextResponse("Internal Server Error", { status: 500 });
    }
}

// Convert UUID to numeric Order Number
function uuidToOrderNumber(id: number): number {

    return id + 10299
}

// Convert numeric Order Number back to UUID
function orderNumberToUuid(orderNumber: number): number {
    return orderNumber - 10299
}

