import { NextRequest, NextResponse } from 'next/server';
import { resolveCrmAccess } from '@/features/crm/reports/server/context';
import { parseSharedReportFilters } from '@/features/crm/reports/server/filters/shared';
import { getCrmPipelineReportResponse } from '@/features/crm/reports/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET(request: NextRequest) {
  try {
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmReportRead
    });

    return NextResponse.json(
      await getCrmPipelineReportResponse(
        resolveCrmAccess({
          organizationId: organization.id,
          userId: session.user.id,
          membership
        }),
        parseSharedReportFilters(request.nextUrl.searchParams)
      )
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

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