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

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || 'sk_test_mock', {
  apiVersion: '2024-06-20' as any,
});

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, isB2B } = body;

    // 1. Validare curs
    let course = await db.course.findUnique({
      where: { id: courseId }
    });

    // Fallback for dynamic packages from the configurator (which have fake IDs)
    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({ error: "Unauthorized" }, { status: 401 });
      }

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

      if (existingUser) {
        return NextResponse.json({ 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;
    }

    const activeTotal = totalAmount || course.price || 0;

    // 2. Creare Comandă temporară (PENDING)
    const orderNumber = `RIMA-${Date.now()}`;
    const order = await db.order.create({
      data: {
        orderNumber,
        userId: userId as string,
        totalAmount: activeTotal,
        status: "PENDING",
        paymentMethod: "CARD",
        isB2B,
        billingName: `${billingInfo.firstName} ${billingInfo.lastName}`,
        billingEmail: billingInfo.email,
        billingPhone: billingInfo.phone,
        billingAddress: billingInfo.address,
        companyName: billingInfo.companyName,
        companyCUI: billingInfo.cui,
        companyRegCom: billingInfo.regCom,
        items: {
          create: {
            courseId: course.id,
            price: activeTotal,
            quantity: 1
          }
        }
      }
    });

    // 3. Creare sesiune Stripe
    const stripeSession = await stripe.checkout.sessions.create({
      mode: 'payment',
      customer_email: billingInfo.email,
      client_reference_id: order.id,
      line_items: [
        {
          price_data: {
            currency: 'ron',
            product_data: {
              name: course.title,
              description: course.description || undefined,
            },
            unit_amount: Math.round(activeTotal * 100), // in bani
          },
          quantity: 1,
        },
      ],
      success_url: `${process.env.NEXT_PUBLIC_APP_URL}/checkout/success?order_id=${order.id}`,
      cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/checkout?course_id=${course.id}&canceled=true`,
      metadata: {
        orderId: order.id,
        courseId: course.id,
        userId: userId as string
      }
    });

    return NextResponse.json({ url: stripeSession.url });

  } catch (error: any) {
    console.error("[STRIPE_CREATE_SESSION]", error);
    return NextResponse.json({ error: "Eroare la procesarea plății cu cardul." }, { status: 500 });
  }
}

