import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";
import { getAdminUser } from "@/lib/auth";

export async function GET() {
  const adminUser = await getAdminUser();

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

  try {
    const admin = await prisma.master_admin_users.findFirst({
      where: {
        id: adminUser.adminId,
        active_status: true,
        delete_status: false,
      },
      select: {
        id: true,
        user_name: true,
        user_email: true,
        phone_number: true,
      },
    });

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

    return NextResponse.json({ success: true, data: admin });
  } catch (error) {
    console.error(error);
    return NextResponse.json(
      { success: false, message: "Failed to load profile" },
      { status: 500 }
    );
  }
}

export async function PUT(req: Request) {
  const adminUser = await getAdminUser();

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

  try {
    const body = await req.json();
    const { name, contact, email, current_password, new_password } = body;

    if (!name || !email) {
      return NextResponse.json(
        { success: false, message: "Name and email are required" },
        { status: 400 }
      );
    }

    const existingAdmin = await prisma.master_admin_users.findFirst({
      where: {
        id: adminUser.adminId,
        active_status: true,
        delete_status: false,
      },
    });

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

    // If email is changing, make sure it's not already used by another admin
    if (email !== existingAdmin.user_email) {
      const emailInUse = await prisma.master_admin_users.findFirst({
        where: {
          user_email: email,
          id: { not: adminUser.adminId },
          delete_status: false,
        },
      });

      if (emailInUse) {
        return NextResponse.json(
          { success: false, message: "Email is already in use" },
          { status: 400 }
        );
      }
    }

    const updateData: Record<string, unknown> = {
      user_name: name,
      user_email: email,
      phone_number: contact || null,
    };

    if (new_password) {
      if (!current_password) {
        return NextResponse.json(
          { success: false, message: "Current password is required" },
          { status: 400 }
        );
      }

      const match = await bcrypt.compare(
        current_password,
        existingAdmin.user_password
      );

      if (!match) {
        return NextResponse.json(
          { success: false, message: "Current password is incorrect" },
          { status: 400 }
        );
      }

      updateData.user_password = await bcrypt.hash(new_password, 10);
    }

    const updated = await prisma.master_admin_users.update({
      where: { id: adminUser.adminId },
      data: updateData,
      select: {
        id: true,
        user_name: true,
        user_email: true,
        phone_number: true,
      },
    });

    return NextResponse.json({
      success: true,
      message: "Profile updated successfully",
      data: updated,
    });
  } catch (error) {
    console.error(error);
    return NextResponse.json(
      { success: false, message: "Failed to update profile" },
      { status: 500 }
    );
  }
}