import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { auth } from "@/lib/auth";
import bcrypt from "bcryptjs";

export async function POST(req: Request) {
  try {
    const session = await auth();
    let userId = session?.user?.id;

    const body = await req.json();
    const { courseId, billingInfo, employeesCount, employeeData, totalAmount, authMode, registerPassword, paymentMethod } = body;

    if (!courseId) {
      return NextResponse.json({ success: false, error: "Lipsește ID-ul cursului." }, { status: 400 });
    }

    let course = await db.course.findUnique({
      where: { id: courseId },
    });

    if (!course) {
      course = await db.course.findFirst({
        where: { title: "Pachet Personalizat" }
      });
      if (!course) {
        course = await db.course.create({
          data: {
            title: "Pachet Personalizat",
            slug: "pachet-personalizat",
            description: "Pachet de curs configurat dinamic.",
            price: 0
          }
        });
      }
    }

    if (!userId) {
      if (!authMode || authMode === "login") {
        return NextResponse.json({ success: false, error: "Neautorizat" }, { status: 401 });
      }

      // Check if user exists
      const existingUser = await db.user.findUnique({
        where: { email: billingInfo.email },
      });

      if (existingUser) {
        return NextResponse.json({ success: false, error: "Acest email este deja asociat unui cont. Te rugăm să te autentifici." }, { status: 400 });
      }

      // Create new user
      const hashedPassword = await bcrypt.hash(registerPassword || "secret123", 10);
      const newUser = await db.user.create({
        data: {
          firstName: billingInfo.firstName,
          lastName: billingInfo.lastName,
          email: billingInfo.email,
          passwordHash: hashedPassword,
        },
      });
      userId = newUser.id;
    }

    // Check if user is already enrolled
    const existingEnrollment = await db.enrollment.findUnique({
      where: {
        userId_courseId: {
          userId,
          courseId: course.id,
        },
      },
    });

    if (existingEnrollment) {
      return NextResponse.json({ success: false, error: "Ești deja înscris la acest curs." }, { status: 400 });
    }

    const payMethod = paymentMethod || "transfer";
    const status = (payMethod === "transfer") ? "SUSPENDED" : "ACTIVE";

    // 1. Transaction to create Order, OrderItem, Invoice, and Enrollment
    const result = await db.$transaction(async (tx) => {
      // Get next order number
      const orderCount = await tx.order.count();
      const orderNumber = `RIMA-${2000 + orderCount}`;

      // Create Order
      const newOrder = await tx.order.create({
        data: {
          userId: userId as string,
          orderNumber,
          status: payMethod === "card" || payMethod === "paypal" ? "COMPLETED" : "PENDING",
          totalAmount: totalAmount || course.price || 0,
          paymentMethod: payMethod.toUpperCase(),
          
          billingName: `${billingInfo.firstName} ${billingInfo.lastName}`,
          billingEmail: billingInfo.email,
          billingPhone: billingInfo.phone,
          billingAddress: billingInfo.address,
          
          isB2B: billingInfo.isB2B || false,
          companyName: billingInfo.isB2B ? billingInfo.companyName : null,
          companyCUI: billingInfo.isB2B ? billingInfo.cui : null,
          companyRegCom: billingInfo.isB2B ? billingInfo.regCom : null,

          items: {
            create: {
              courseId: course.id,
              price: totalAmount || course.price || 0,
              quantity: 1,
            }
          }
        },
      });

      // Create Invoice Draft
      const invoiceCount = await tx.invoice.count();
      const newInvoice = await tx.invoice.create({
        data: {
          orderId: newOrder.id,
          invoiceNumber: 1000 + invoiceCount,
          totalAmount: totalAmount || course.price || 0,
          taxAmount: 0, // Simplified tax
          status: payMethod === "card" || payMethod === "paypal" ? "ISSUED" : "DRAFT",
        }
      });

      // Create Enrollment
      const newEnrollment = await tx.enrollment.create({
        data: {
          userId: userId as string,
          courseId: course.id,
          status,
        },
      });

      return { newOrder, newInvoice, newEnrollment };
    });

    return NextResponse.json({ success: true, data: result.newEnrollment });
  } catch (error) {
    console.error("[/api/enrollments POST]", error);
    return NextResponse.json(
      { success: false, error: "Eroare la procesarea comenzii." },
      { status: 500 }
    );
  }
}
