<?php
namespace App\Jobs;
use App\Models\{Asset,LedgerEntry,Merchant,PayoutAddressAllowlist,SettlementBatch};
use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Str;
final class AutoSettleMerchantBalancesJob implements ShouldQueue {use Dispatchable,InteractsWithQueue,Queueable,SerializesModels;public function __construct(public string $environment){$this->onQueue('payouts');}
 public function handle():void{Merchant::where('status','active')->select('id')->chunkById(100,function($merchants){$assets=Asset::where('enabled',true)->where('payout_enabled',true)->get();foreach($merchants as $m){foreach($assets as $asset){$wallet=PayoutAddressAllowlist::where('merchant_id',$m->id)->where('asset_id',$asset->id)->where('environment',$this->environment)->where('status','active')->where('is_default',true)->where('available_at','<=',now())->first();if(!$wallet)continue;$balance=(string)LedgerEntry::whereHas('account',fn($q)=>$q->where('merchant_id',$m->id)->where('asset_id',$asset->id)->where('type','merchant_available'))->selectRaw("COALESCE(SUM(CASE WHEN direction='credit' THEN amount_atomic ELSE -amount_atomic END),0) as balance")->value('balance');if(bccomp($balance,(string)$asset->min_amount_atomic,0)<0)continue;$s=SettlementBatch::create(['public_id'=>'set_'.Str::ulid(),'merchant_id'=>$m->id,'asset_id'=>$asset->id,'payout_wallet_id'=>$wallet->id,'environment'=>$this->environment,'status'=>'pending','amount_atomic'=>$balance,'fee_atomic'=>config('gateway.tron.default_fee_atomic','1000000'),'metadata'=>['source'=>'auto_settlement']]);CreateSettlementPayoutJob::dispatch($s->id)->onQueue('payouts');}}});}
}