import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { Admin } from '@/models/Admin';
import { requireAdmin, requireSuperAdmin } from '@/lib/auth';

interface Params {
  params: { id: string };
}

// GET /api/admins/[id]
export async function GET(req: NextRequest, { params }: Params) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const admin = await Admin.findById(params.id).select('-password');
    if (!admin) {
      return NextResponse.json({ success: false, error: 'Admin not found' }, { status: 404 });
    }

    return NextResponse.json({ success: true, admin });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error fetching admin' },
      { status: 500 }
    );
  }
}

// PUT /api/admins/[id] - Allows Super Admin OR self admin to update profile
export async function PUT(req: NextRequest, { params }: Params) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  const isSelf = auth.user.id === params.id;
  const isSuperAdmin = auth.user.role === 'super_admin';

  if (!isSelf && !isSuperAdmin) {
    return NextResponse.json(
      { success: false, error: 'Forbidden: You can only edit your own profile' },
      { status: 403 }
    );
  }

  try {
    await dbConnect();
    const body = await req.json();
    const { name, email, role, isActive, avatarUrl, currentPassword, password } = body;

    const admin = await Admin.findById(params.id).select('+password');
    if (!admin) {
      return NextResponse.json({ success: false, error: 'Admin not found' }, { status: 404 });
    }

    // Update Email (Check for duplicate)
    if (email && email.toLowerCase() !== admin.email.toLowerCase()) {
      const existing = await Admin.findOne({ email: email.toLowerCase() });
      if (existing) {
        return NextResponse.json(
          { success: false, error: 'An admin with this email address already exists' },
          { status: 409 }
        );
      }
      admin.email = email.toLowerCase();
    }

    if (name) admin.name = name;
    if (typeof avatarUrl === 'string') admin.avatarUrl = avatarUrl;

    // Only Super Admin can change roles or active status
    if (isSuperAdmin) {
      if (role && ['admin', 'super_admin'].includes(role)) admin.role = role;
      if (typeof isActive === 'boolean') admin.isActive = isActive;
    }

    // Handle Password Update / Reset
    if (password) {
      if (password.length < 6) {
        return NextResponse.json(
          { success: false, error: 'New password must be at least 6 characters long' },
          { status: 400 }
        );
      }

      // If updating own password, verify current password if supplied
      if (isSelf && currentPassword) {
        const isMatch = await admin.comparePassword(currentPassword);
        if (!isMatch) {
          return NextResponse.json(
            { success: false, error: 'Current password is incorrect' },
            { status: 400 }
          );
        }
      }

      admin.password = password; // Pre-save hook will hash it
    }

    await admin.save();

    return NextResponse.json({
      success: true,
      message: 'Admin profile updated successfully',
      admin: {
        id: admin._id,
        _id: admin._id,
        name: admin.name,
        email: admin.email,
        role: admin.role,
        isActive: admin.isActive,
        avatarUrl: admin.avatarUrl,
      },
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error updating admin profile' },
      { status: 500 }
    );
  }
}

// DELETE /api/admins/[id]
export async function DELETE(req: NextRequest, { params }: Params) {
  const auth = requireSuperAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();

    // Prevent deleting your own logged-in account
    if (auth.user.id === params.id) {
      return NextResponse.json(
        { success: false, error: 'Cannot delete your own super admin account' },
        { status: 400 }
      );
    }

    const deleted = await Admin.findByIdAndDelete(params.id);
    if (!deleted) {
      return NextResponse.json({ success: false, error: 'Admin not found' }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      message: 'Admin account deleted successfully',
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error deleting admin' },
      { status: 500 }
    );
  }
}
