import { NextRequest, NextResponse } from 'next/server';
import { AuthError, requireUserManagementAccess } from '@/lib/auth/session';
import {
  getUserMasterOptionsForAccess,
  listUsersForAccess,
  upsertUserForAccess
} from '@/features/users/server/user-data';

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) {
  try {
    const userManagementAccess = await requireUserManagementAccess();
    const access = getAccessContext(userManagementAccess);
    const mode = request.nextUrl.searchParams.get('mode');

    if (mode === 'options') {
      const options = await getUserMasterOptionsForAccess({ access });
      return NextResponse.json(options);
    }

    const { searchParams } = request.nextUrl;
    const result = await listUsersForAccess({
      filters: {
        page: Number(searchParams.get('page') ?? 1),
        limit: Number(searchParams.get('limit') ?? 10),
        roles: searchParams.get('roles') ?? undefined,
        search: searchParams.get('search') ?? undefined,
        sort: searchParams.get('sort') ?? undefined
      },
      access
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Users loaded successfully',
      total_users: result.total,
      offset: result.offset,
      limit: result.limit,
      users: result.users
    });
  } 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 });
    }

    console.error('GET /api/users failed', error);

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

export async function POST(request: NextRequest) {
  try {
    const userManagementAccess = await requireUserManagementAccess();
    const access = getAccessContext(userManagementAccess);
    const body = await request.json();
    const userId = await upsertUserForAccess({
      payload: body,
      access
    });

    return NextResponse.json(
      {
        success: true,
        message: 'User saved successfully',
        user_id: userId
      },
      { status: 201 }
    );
  } 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 === 'ORGANIZATION_REQUIRED') {
        return NextResponse.json({ message: 'Organizer is required' }, { status: 400 });
      }

      if (error.message === 'PASSWORD_REQUIRED') {
        return NextResponse.json(
          { message: 'Password is required and must be at least 8 characters' },
          { status: 400 }
        );
      }

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

      if (error.message === 'ADMIN_ROLE_FORBIDDEN') {
        return NextResponse.json(
          { message: 'Only super admins can assign admin access' },
          { status: 403 }
        );
      }
    }

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