import { NextResponse } from 'next/server';
import { listMasterOptionCategories } from '@/features/foundation/master-options/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET() {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmMasterOptionRead
    });
    const items = await listMasterOptionCategories(organization.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Master option categories loaded successfully',
      items: items.map((item) => ({
        category: item.category,
        total_items: item.totalItems,
        active_items: item.activeItems
      }))
    });
  } 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 master option categories' }, { status: 500 });
  }
}
