import { NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { user, userPortRoles, userProfiles } from '@/lib/db/schema';
import { errorResponse } from '@/lib/errors';

/**
 * GET /api/v1/admin/users/picker
 *
 * Lightweight list of users in the active port, used by admin form
 * user-select dropdowns (e.g. linking a CRM user to a Documenso recipient
 * slot). Returns only the fields needed to render an option: id, email,
 * name. Excludes deactivated users.
 *
 * Gated on `admin.manage_settings` - anyone editing per-port admin
 * settings can already see all the configured Documenso recipient
 * email/name values, so revealing the user roster to them doesn't
 * widen the trust boundary. Tighter than the full `admin/users` GET
 * (which is `admin.manage_users`-gated).
 */
export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx) => {
    try {
      const rows = await db
        .select({
          id: user.id,
          email: user.email,
          name: user.name,
          isActive: userProfiles.isActive,
        })
        .from(user)
        .innerJoin(userPortRoles, eq(userPortRoles.userId, user.id))
        .leftJoin(userProfiles, eq(userProfiles.userId, user.id))
        .where(and(eq(userPortRoles.portId, ctx.portId)));

      // Dedupe by id (a user with multiple role rows in this port would
      // otherwise repeat) and drop deactivated profiles.
      const seen = new Set<string>();
      const data = rows
        .filter((r) => r.isActive !== false)
        .filter((r) => {
          if (seen.has(r.id)) return false;
          seen.add(r.id);
          return true;
        })
        .map(({ id, email, name }) => ({ id, email, name }));
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
