import { NextResponse } from 'next/server';
import { processApprovalAutomation } from '@/features/foundation/approval-automation/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function POST() {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalAutomationRun
    });
    const result = await processApprovalAutomation(organization.id, session.user.id);

    return NextResponse.json({
      success: true,
      message: 'Approval automation completed 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 run approval automation' }, { status: 500 });
  }
}
