import { NextRequest, NextResponse } from 'next/server';
import { getCrmDashboardData } from '@/features/crm/dashboard/server/service';
import { buildCrmSecurityContext } from '@/features/crm/security/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET(request: NextRequest) {
  try {
    const { session, membership, organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDashboardRead
    });
    const searchParams = request.nextUrl.searchParams;
    const securityContext = buildCrmSecurityContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const data = await getCrmDashboardData(securityContext, {
      dateFrom: searchParams.get('dateFrom'),
      dateTo: searchParams.get('dateTo'),
      branch: searchParams.get('branch'),
      salesman: searchParams.get('salesman'),
      projectPartyRole: searchParams.get('projectPartyRole'),
      productType: searchParams.get('productType')
    });

    return NextResponse.json(data);
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

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

    return NextResponse.json(
      {
        message: 'Unable to load CRM dashboard',
        ...(process.env.NODE_ENV !== 'production' && error instanceof Error
          ? {
              detail: error.message,
              cause:
                error.cause instanceof Error
                  ? error.cause.message
                  : error.cause
                    ? String(error.cause)
                    : null
            }
          : {})
      },
      { status: 500 }
    );
  }
}
