<?php
/**
 * سودانا — DecisionEngine v2
 * Returns action list only. No execution. No DB.
 */
class DecisionEngine {

    public static function handle(string $event, array $payload): array {
        switch ($event) {
            case 'booking.completed':
                return self::onBookingCompleted($payload);
            case 'subscription.offer':
                return [['type'=>'subscription.offer','data'=>$payload]];
            case 'flow.abandoned':
                return [['type'=>'followup.recovery','data'=>$payload]];
            case 'ai_engine.used':
                return [['type'=>'usage.track','data'=>$payload]];
            case 'payment.confirmed':
                // Unified: handles BOTH offline admin approval AND gateway webhook
                // receipt is already created by FinancialAgent::confirmPayment()
                $tasks = [['type'=>'payment.post_confirm','data'=>$payload]];
                if (!empty($payload['gateway'])) {
                    $tasks[] = ['type'=>'payment.gateway.notify','data'=>$payload];
                }
                return $tasks;
            case 'payment.reversed':
                return [['type'=>'payment.post_refund','data'=>$payload]];
            case 'financial.audit':
                return [['type'=>'financial.audit.run','data'=>$payload]];
            case 'flow.started':
                return [['type'=>'flow.notification','data'=>$payload]];
            case 'billing.required':
                return [['type'=>'billing.notify.user','data'=>$payload]];
            case 'tool.executed':
                return [['type'=>'tool.postprocess','data'=>$payload]];
            case 'risk.block':
                return [['type'=>'risk.notify.user','data'=>$payload]];
            case 'reconciliation.failed':
                return [['type'=>'recon.alert.admin','data'=>$payload]];
            case 'settlement.requested':
                return [['type'=>'settlement.process','data'=>$payload]];
            default:
                return [];
        }
    }

    private static function onBookingCompleted(array $payload): array {
        $service = $payload['service'] ?? 'medical';
        $actions = [
            ['type'=>'followup.schedule',  'data'=>$payload],
            ['type'=>'subscription.offer', 'data'=>$payload],
        ];
        if (in_array($service, ['medical','family'])) {
            array_unshift($actions, ['type'=>'pharmacy.suggest','data'=>$payload]);
        }
        return $actions;
    }
}
