import { NextResponse } from 'next/server';
import { getPendingApprovalQueue } from '@/features/foundation/approval-automation/server/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.crmApprovalAutomationRead
    });
    const result = await getPendingApprovalQueue(organization.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Pending approval automation queue loaded successfully',
      ...result
    });
  } 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 pending approval queue' },
      { status: 500 }
    );
  }
}
