import { auth } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
import { setUserRole, isAdmin, type UserRole } from '@/lib/clerk-helpers';

export async function POST(req: Request) {
  try {
    // Authenticate the request
    const { userId } = await auth();

    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // Check if the requesting user is an admin
    const requestingUserIsAdmin = await isAdmin(userId);

    if (!requestingUserIsAdmin) {
      return NextResponse.json(
        { error: 'Forbidden: Admin access required' },
        { status: 403 }
      );
    }

    // Parse request body
    const body = await req.json();
    const { targetUserId, role } = body;

    // Validate inputs
    if (!targetUserId || typeof targetUserId !== 'string') {
      return NextResponse.json(
        { error: 'Invalid or missing targetUserId' },
        { status: 400 }
      );
    }

    if (!role || !['admin', 'trainer', 'client'].includes(role)) {
      return NextResponse.json(
        { error: 'Invalid role. Must be admin, trainer, or client' },
        { status: 400 }
      );
    }

    // Prevent admin from changing their own role
    if (userId === targetUserId) {
      return NextResponse.json(
        { error: 'Cannot change your own role' },
        { status: 400 }
      );
    }

    // Set the user's role
    const updatedUser = await setUserRole(targetUserId, role as UserRole);

    return NextResponse.json({
      success: true,
      message: `User role updated to ${role}`,
      user: {
        id: updatedUser.id,
        email: updatedUser.emailAddresses[0]?.emailAddress,
        firstName: updatedUser.firstName,
        lastName: updatedUser.lastName,
        role: updatedUser.publicMetadata.role,
      },
    });
  } catch (error) {
    console.error('Error setting user role:', error);

    if (error instanceof Error && error.message.includes('not found')) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
