<?php
namespace App\Http\Controllers\Api\V1;
use App\Application\Services\Payouts\PayoutStateMachine;use App\Http\Controllers\Controller;use App\Jobs\ApprovePayoutJob;use App\Models\Payout;use App\Support\ApiResponse;use Illuminate\Http\Request;use Illuminate\Support\Facades\DB;
final class PayoutApprovalController extends Controller {public function approve(Request $r,string $payoutId,PayoutStateMachine $sm){$d=$r->validate(['reason'=>['nullable','string','max:1000']]);$p=DB::transaction(function()use($r,$payoutId,$d,$sm){$p=Payout::lockForUpdate()->where('public_id',$payoutId)->firstOrFail();if($p->status!=='pending_approval')abort(409,'Payout is not pending approval.');$p->update(['approved_by'=>$r->user()->id,'approved_at'=>now()]);$p->approvals()->create(['approver_id'=>$r->user()->id,'decision'=>'approved','reason'=>$d['reason']??null,'decided_at'=>now()]);$sm->transition($p,'approved');return $p;});ApprovePayoutJob::dispatch($p->id)->onQueue('payouts')->afterCommit();return ApiResponse::success(['payout_id'=>$p->public_id,'status'=>'approved']);}}
