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

// Endpoint for WordPress / WooCommerce Webhooks
// URL: https://lms.rima-academy.com/api/webhooks/wordpress
// POST Method
export async function POST(req: Request) {
  try {
    const body = await req.json();
    const { action, user, courseId, secret } = body;

    // 1. Verify Secret Key (Set this in WordPress webhook settings)
    const WP_WEBHOOK_SECRET = process.env.WP_WEBHOOK_SECRET || "rima-academy-secret-key-2024";
    if (secret !== WP_WEBHOOK_SECRET) {
      return NextResponse.json({ error: "Unauthorized. Invalid secret." }, { status: 401 });
    }

    // 2. Handle 'enroll_user' action (e.g., WooCommerce completed order)
    if (action === "enroll_user") {
      if (!user?.email || !courseId) {
        return NextResponse.json({ error: "Missing user email or courseId." }, { status: 400 });
      }

      // Check if user exists
      let dbUser = await db.user.findUnique({
        where: { email: user.email },
      });

      // If new user, create account with a random password
      if (!dbUser) {
        const randomPassword = Math.random().toString(36).slice(-8) + "Aa1!";
        const hashedPassword = await bcrypt.hash(randomPassword, 10);
        
        dbUser = await db.user.create({
          data: {
            email: user.email,
            firstName: user.firstName || "Student",
            lastName: user.lastName || "",
            passwordHash: hashedPassword,
            role: "STUDENT",
          },
        });
      }

      // Create or update enrollment
      const existingEnrollment = await db.enrollment.findFirst({
        where: { userId: dbUser.id, courseId: courseId },
      });

      if (!existingEnrollment) {
        await db.enrollment.create({
          data: {
            userId: dbUser.id,
            courseId: courseId,
            status: "ACTIVE",
          },
        });
      } else if (existingEnrollment.status !== "ACTIVE") {
        await db.enrollment.update({
          where: { id: existingEnrollment.id },
          data: { status: "ACTIVE" },
        });
      }

      return NextResponse.json({ 
        success: true, 
        message: `User ${user.email} successfully enrolled in course ${courseId}.` 
      });
    }

    return NextResponse.json({ error: "Unknown action." }, { status: 400 });

  } catch (error: any) {
    console.error("[WP_WEBHOOK_ERROR]", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
