import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { verifyToken, getTokenFromRequest } from "@/lib/jwt";
import { z } from "zod";

// Schema untuk validasi Mapel
const MapelSchema = z.object({
  kodeMapel: z.string().min(1, "Kode mata pelajaran tidak boleh kosong"),
  namaMapel: z.string().min(1, "Nama mata pelajaran tidak boleh kosong"),
});

// GET - Ambil semua mapel
export async function GET(request: NextRequest) {
  try {
    const token = getTokenFromRequest(request);

    if (!token) {
      return NextResponse.json({ success: false, message: "Token tidak ditemukan" }, { status: 401 });
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json({ success: false, message: "Token tidak valid" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const search = searchParams.get("search") || "";

    const mapel = await prisma.mapel.findMany({
      where: search
        ? {
            OR: [
              { kodeMapel: { contains: search, mode: "insensitive" } },
              { namaMapel: { contains: search, mode: "insensitive" } },
            ],
          }
        : {},
      orderBy: { namaMapel: "asc" },
    });

    return NextResponse.json({
      success: true,
      data: mapel,
    });
  } catch (error) {
    console.error("Error fetching mapel:", error);
    return NextResponse.json({ success: false, message: "Terjadi kesalahan server" }, { status: 500 });
  }
}

// POST - Tambah mapel baru
export async function POST(request: NextRequest) {
  try {
    const token = getTokenFromRequest(request);

    if (!token) {
      return NextResponse.json({ success: false, message: "Token tidak ditemukan" }, { status: 401 });
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json({ success: false, message: "Token tidak valid" }, { status: 401 });
    }

    // Check if user is admin or guru
    if (payload.role !== "ADMIN" && payload.role !== "GURU") {
      return NextResponse.json(
        { success: false, message: "Hanya admin dan guru yang dapat menambah mata pelajaran" },
        { status: 403 },
      );
    }

    const body = await request.json();
    const { kodeMapel, namaMapel } = MapelSchema.parse(body);

    // Check if kode mapel already exists
    const existingMapel = await prisma.mapel.findUnique({
      where: { kodeMapel },
    });

    if (existingMapel) {
      return NextResponse.json({ success: false, message: "Kode mata pelajaran sudah digunakan" }, { status: 400 });
    }

    const mapel = await prisma.mapel.create({
      data: {
        kodeMapel,
        namaMapel,
      },
    });

    return NextResponse.json({
      success: true,
      data: mapel,
      message: "Mata pelajaran berhasil ditambahkan",
    });
  } catch (error) {
    console.error("Error creating mapel:", error);

    if (error instanceof z.ZodError) {
      return NextResponse.json(
        {
          success: false,
          message: "Data tidak valid",
          errors: error.errors,
        },
        { status: 400 },
      );
    }

    return NextResponse.json({ success: false, message: "Terjadi kesalahan server" }, { status: 500 });
  }
}
