import { NextRequest, NextResponse } from 'next/server';
import { AuthError, requireUserManagementAccess } from '@/lib/auth/session';
import {
  deactivateUserForAccess,
  getUserForAccess,
  updateUserForAccess
} from '@/features/users/server/user-data';

type Params = { params: Promise<{ id: string }> };

function getAccessContext(
  access: Awaited<ReturnType<typeof requireUserManagementAccess>>
) {
  return {
    currentUserId: access.session.user.id,
    currentOrganizationId: access.organization.id,
    membershipRole: access.membership.role,
    businessRole: access.session.user.businessRole,
    systemRole: access.session.user.systemRole
  };
}

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const userManagementAccess = await requireUserManagementAccess();
    const access = getAccessContext(userManagementAccess);
    const { id } = await params;
    const user = await getUserForAccess({ id, access });

    if (!user) {
      return NextResponse.json({ message: 'User not found' }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      message: 'User loaded successfully',
      user
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error && error.message === 'FORBIDDEN') {
      return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
    }

    return NextResponse.json({ message: 'Unable to load user' }, { status: 500 });
  }
}

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const userManagementAccess = await requireUserManagementAccess();
    const access = getAccessContext(userManagementAccess);
    const { id } = await params;
    const body = await request.json();

    await updateUserForAccess({
      userId: id,
      payload: body,
      access
    });

    return NextResponse.json({
      success: true,
      message: 'User updated successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      if (error.message === 'FORBIDDEN' || error.message === 'ADMIN_ROLE_FORBIDDEN') {
        return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
      }

      if (error.message === 'USERNAME_EXISTS') {
        return NextResponse.json({ message: 'Username already exists' }, { status: 400 });
      }

      if (error.message === 'NOT_FOUND') {
        return NextResponse.json({ message: 'User not found' }, { status: 404 });
      }
    }

    return NextResponse.json({ message: 'Unable to update user' }, { status: 500 });
  }
}

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const userManagementAccess = await requireUserManagementAccess();
    const access = getAccessContext(userManagementAccess);
    const { id } = await params;

    await deactivateUserForAccess({
      userId: id,
      access
    });

    return NextResponse.json({
      success: true,
      message: 'User deactivated successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      if (error.message === 'FORBIDDEN') {
        return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
      }

      if (error.message === 'NOT_FOUND') {
        return NextResponse.json({ message: 'User not found' }, { status: 404 });
      }
    }

    return NextResponse.json({ message: 'Unable to deactivate user' }, { status: 500 });
  }
}
