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

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

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

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