import { NextRequest, NextResponse } from 'next/server';
import { listEnquiryProjectParties } from '@/features/crm/enquiries/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = {
  params: Promise<{ id: string }>;
};

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmEnquiryRead
    });
    const items = await listEnquiryProjectParties(id, organization.id, {
      organizationId: organization.id,
      userId: session.user.id,
      membershipRole: membership.role,
      businessRole: membership.businessRole
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Enquiry project parties loaded successfully',
      items
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json(
      { message: 'Unable to load enquiry project parties' },
      { status: 500 }
    );
  }
}
