import { NextRequest, NextResponse } from 'next/server';
import { getCrmDashboardData } from '@/features/crm/dashboard/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 data = await getCrmDashboardData(
      {
        organizationId: organization.id,
        userId: session.user.id,
        membershipRole: membership.role,
        businessRole: membership.businessRole,
        permissions: membership.permissions
      },
      {
        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' }, { status: 500 });
  }
}
