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

import { prisma } from "@/lib/prisma";
import { getAdminUser } from "@/lib/auth";

export async function GET(
  req: Request,
  {
    params,
  }: {
    params: Promise<{
      id: string;
    }>;
  }
) {
  try {
    const admin =
      await getAdminUser();

    if (!admin) {
      return NextResponse.json(
        {
          success: false,
          message: "Unauthorized",
        },
        {
          status: 401,
        }
      );
    }

    const { id } = await params;

    const student =
      await prisma.students.findUnique({
        where: {
          id: Number(id),
        },
      });

    if (!student) {
      return NextResponse.json(
        {
          success: false,
          message:
            "Student not found",
        },
        {
          status: 404,
        }
      );
    }

    return NextResponse.json({
      success: true,
      data: student,
    });
  } catch (error) {
    console.error(
      "GET Student Error:",
      error
    );

    return NextResponse.json(
      {
        success: false,
        message:
          error instanceof Error
            ? error.message
            : "Something went wrong",
      },
      {
        status: 500,
      }
    );
  }
}

export async function PUT(
  req: Request,
  {
    params,
  }: {
    params: Promise<{
      id: string;
    }>;
  }
) {
  try {
    const admin =
      await getAdminUser();

    if (!admin) {
      return NextResponse.json(
        {
          success: false,
          message: "Unauthorized",
        },
        {
          status: 401,
        }
      );
    }

    const { id } = await params;

    const body = await req.json();

    const existingStudent =
      await prisma.students.findUnique({
        where: {
          id: Number(id),
        },
      });

    if (!existingStudent) {
      return NextResponse.json(
        {
          success: false,
          message:
            "Student not found",
        },
        {
          status: 404,
        }
      );
    }

    const updateData: any = {
      student_id:
        body.student_id,
      name: body.name,
      contact: body.contact,
      email: body.email,
    };

    if (
      body.password &&
      body.password.trim() !== ""
    ) {
      updateData.password =
        await bcrypt.hash(
          body.password,
          10
        );
    }

    const student =
      await prisma.students.update({
        where: {
          id: Number(id),
        },
        data: updateData,
      });

    return NextResponse.json({
      success: true,
      message:
        "Student updated successfully",
      data: student,
    });
  } catch (error) {
    console.error(
      "UPDATE Student Error:",
      error
    );

    return NextResponse.json(
      {
        success: false,
        message:
          error instanceof Error
            ? error.message
            : "Something went wrong",
      },
      {
        status: 500,
      }
    );
  }
}

export async function DELETE(
  req: Request,
  {
    params,
  }: {
    params: Promise<{
      id: string;
    }>;
  }
) {
  try {
    const admin =
      await getAdminUser();

    if (!admin) {
      return NextResponse.json(
        {
          success: false,
          message: "Unauthorized",
        },
        {
          status: 401,
        }
      );
    }

    const { id } = await params;

    const existingStudent =
      await prisma.students.findUnique({
        where: {
          id: Number(id),
        },
      });

    if (!existingStudent) {
      return NextResponse.json(
        {
          success: false,
          message:
            "Student not found",
        },
        {
          status: 404,
        }
      );
    }

    await prisma.students.delete({
      where: {
        id: Number(id),
      },
    });

    return NextResponse.json({
      success: true,
      message:
        "Student deleted successfully",
    });
  } catch (error) {
    console.error(
      "DELETE Student Error:",
      error
    );

    return NextResponse.json(
      {
        success: false,
        message:
          error instanceof Error
            ? error.message
            : "Something went wrong",
      },
      {
        status: 500,
      }
    );
  }
}