import { NextResponse } from 'next/server';
import { z } from 'zod';
import { listCrmRoleProfiles } from '@/features/foundation/role-management/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET() {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmRoleRead
    });
    const result = await listCrmRoleProfiles(organization.id, session.user.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'CRM roles loaded successfully',
      ...result
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof z.ZodError) {
      return NextResponse.json({ message: error.issues[0]?.message ?? 'Invalid request' }, { status: 400 });
    }

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