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

import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { ports as portsTable } from '@/lib/db/schema/ports';
import { userPortRoles, userProfiles } from '@/lib/db/schema/users';
import { errorResponse } from '@/lib/errors';

/**
 * Bootstrap-friendly ports list for the calling user.
 *
 * M-NEW-1: this endpoint INTENTIONALLY skips `withAuth`'s port-context
 * requirement. Callers hit /me/ports specifically to LEARN which ports
 * they have access to - they can't have selected one yet, so the
 * X-Port-Id header is by definition absent on the first call. Pre-fix
 * this meant non-super-admins got a 400 "Port context required" and
 * the client had to special-case the response shape.
 *
 * Auth is still enforced (session check); permissions logic skipped
 * because the endpoint exposes only IDs+slugs+names of ports the user
 * is already a member of - same surface area as a `me` profile read.
 */
export async function GET() {
  try {
    const session = await auth.api.getSession({ headers: await headers() });
    if (!session?.user) {
      return NextResponse.json({ error: 'Authentication required' }, { status: 401 });
    }

    const profile = await db.query.userProfiles.findFirst({
      where: eq(userProfiles.userId, session.user.id),
    });
    if (!profile || !profile.isActive) {
      return NextResponse.json({ error: 'Account disabled' }, { status: 403 });
    }

    if (profile.isSuperAdmin) {
      const all = await db.query.ports.findMany({
        where: eq(portsTable.isActive, true),
        orderBy: portsTable.createdAt,
        columns: { id: true, slug: true, name: true },
      });
      return NextResponse.json({ data: all });
    }

    const memberships = await db.query.userPortRoles.findMany({
      where: eq(userPortRoles.userId, profile.userId),
      with: { port: { columns: { id: true, slug: true, name: true } } },
    });
    const data = memberships.map((m) => m.port);
    return NextResponse.json({ data });
  } catch (error) {
    return errorResponse(error);
  }
}
