import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { getAdminUser } from "@/lib/auth";
import { NextResponse } from "next/server";
import { sendMail } from "@/lib/mailer";
import { welcomeEmailTemplate } from "@/lib/email-templates";

export async function GET() {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ success: false }, { status: 401 });

  const students = await prisma.students.findMany({
    orderBy: { created_at: "desc" },
  });

  return NextResponse.json({ success: true, data: students });
}

export async function POST(req: Request) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ success: false }, { status: 401 });

  try {
    const body = await req.json();

    // ── Validation ──
    if (!body.student_id?.trim()) {
      return NextResponse.json({ success: false, message: "Student ID is required" }, { status: 400 });
    }
    if (!body.name?.trim()) {
      return NextResponse.json({ success: false, message: "Name is required" }, { status: 400 });
    }
    if (!body.email?.trim()) {
      return NextResponse.json({ success: false, message: "Email is required" }, { status: 400 });
    }
    if (!body.contact?.trim()) {
      return NextResponse.json({ success: false, message: "Contact is required" }, { status: 400 });
    }
    if (!body.password) {
      return NextResponse.json({ success: false, message: "Password is required" }, { status: 400 });
    }

    // ── Check duplicates ──
    const existingEmail = await prisma.students.findUnique({
      where: { email: body.email },
    });
    if (existingEmail) {
      return NextResponse.json({ success: false, message: "Email already exists" }, { status: 400 });
    }

    const existingId = await prisma.students.findUnique({
      where: { student_id: body.student_id },
    });
    if (existingId) {
      return NextResponse.json({ success: false, message: "Student ID already exists" }, { status: 400 });
    }

    // ── Hash password & create ──
    const plainPassword = body.password;
    const hashedPassword = await bcrypt.hash(plainPassword, 10);

    const student = await prisma.students.create({
      data: {
        student_id: body.student_id,
        name: body.name,
        contact: body.contact,
        email: body.email,
        password: hashedPassword,
        email_verified: true,
        status: "active",
      },
    });

    // ── Send welcome email with credentials ──
    try {
      await sendMail({
        to: student.email,
        subject: "Your RKDA student account has been created",
        html: welcomeEmailTemplate(
          student.name,
          student.student_id,
          student.email,
          plainPassword,
          `${process.env.NEXT_PUBLIC_APP_URL}/student/login`
        ),
      });
    } catch (mailErr) {
      console.error("Welcome Email Send Error:", mailErr);
    }

    return NextResponse.json({ success: true, data: student });
  } catch (err) {
    console.error("Create student error:", err);
    return NextResponse.json({ success: false, message: "Failed to create student" }, { status: 500 });
  }
}