<?php
namespace App\Http\Controllers\Api\V1;
use App\Domain\Blockchain\Contracts\BlockchainGateway;
use App\Http\Controllers\Controller;
use App\Models\{Asset,PayoutAddressAllowlist};
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Throwable;
final class PayoutWalletController extends Controller {
 public function index(Request $r){$m=$r->attributes->get('merchant');$env=$r->attributes->get('environment');$q=PayoutAddressAllowlist::with('asset')->where('merchant_id',$m->id)->where('environment',$env)->whereNull('archived_at')->latest('id');return ApiResponse::success($q->get()->map(fn($w)=>$this->resource($w))->values());}
 public function store(Request $r,BlockchainGateway $gateway){$d=$r->validate(['pay_currency'=>['required','string','max:20'],'address'=>['required','string','max:255'],'label'=>['nullable','string','max:100'],'is_default'=>['nullable','boolean'],'metadata'=>['nullable','array']]);$m=$r->attributes->get('merchant');$env=$r->attributes->get('environment');$asset=Asset::where('code',strtoupper($d['pay_currency']))->where('enabled',true)->first();if(!$asset)return ApiResponse::error('UNSUPPORTED_CURRENCY','The requested asset or network is not enabled.',422);try{$valid=$gateway->validateAddress($asset->network,$d['address']);}catch(Throwable){$valid=strlen(trim($d['address']))>=20;}if(!$valid)return ApiResponse::error('INVALID_PAYOUT_ADDRESS','The payout wallet address is not valid for this network.',422);$wallet=DB::transaction(function()use($m,$env,$asset,$d){if(!empty($d['is_default']))PayoutAddressAllowlist::where('merchant_id',$m->id)->where('asset_id',$asset->id)->where('environment',$env)->update(['is_default'=>false]);$existing=PayoutAddressAllowlist::where('merchant_id',$m->id)->where('asset_id',$asset->id)->where('environment',$env)->where('address',$d['address'])->first();if($existing){$existing->update(['label'=>$d['label']??$existing->label,'status'=>'active','is_default'=>(bool)($d['is_default']??$existing->is_default),'metadata'=>$d['metadata']??$existing->metadata,'archived_at'=>null,'available_at'=>now(),'verified_at'=>now()]);return $existing->fresh('asset');}return PayoutAddressAllowlist::create(['public_id'=>'pwa_'.Str::ulid(),'merchant_id'=>$m->id,'asset_id'=>$asset->id,'network'=>$asset->network,'environment'=>$env,'address'=>$d['address'],'label'=>$d['label']??null,'status'=>'active','is_default'=>(bool)($d['is_default']??false),'available_at'=>now(),'verified_at'=>now(),'metadata'=>$d['metadata']??[]])->load('asset');});return ApiResponse::success($this->resource($wallet),201);}
 public function show(Request $r,string $id){$w=$this->find($r,$id);if(!$w)return ApiResponse::error('PAYOUT_WALLET_NOT_FOUND','The requested payout wallet does not exist.',404);return ApiResponse::success($this->resource($w));}
 public function update(Request $r,string $id){$w=$this->find($r,$id);if(!$w)return ApiResponse::error('PAYOUT_WALLET_NOT_FOUND','The requested payout wallet does not exist.',404);$d=$r->validate(['label'=>['nullable','string','max:100'],'status'=>['nullable','in:active,disabled'],'is_default'=>['nullable','boolean'],'metadata'=>['nullable','array']]);DB::transaction(function()use($w,$d){if(array_key_exists('is_default',$d)&&$d['is_default'])PayoutAddressAllowlist::where('merchant_id',$w->merchant_id)->where('asset_id',$w->asset_id)->where('environment',$w->environment)->where('id','!=',$w->id)->update(['is_default'=>false]);$w->fill($d)->save();});return ApiResponse::success($this->resource($w->fresh('asset')));}
 public function destroy(Request $r,string $id){$w=$this->find($r,$id);if(!$w)return ApiResponse::error('PAYOUT_WALLET_NOT_FOUND','The requested payout wallet does not exist.',404);$w->update(['status'=>'disabled','is_default'=>false,'archived_at'=>now()]);return ApiResponse::success($this->resource($w->fresh('asset')));}
 private function find(Request $r,string $id):?PayoutAddressAllowlist{return PayoutAddressAllowlist::with('asset')->where('public_id',$id)->where('merchant_id',$r->attributes->get('merchant')->id)->where('environment',$r->attributes->get('environment'))->whereNull('archived_at')->first();}
 private function resource(PayoutAddressAllowlist $w):array{return ['id'=>$w->public_id,'pay_currency'=>$w->asset?->code,'network'=>$w->network?:$w->asset?->network,'address'=>$w->address,'label'=>$w->label,'status'=>$w->status,'is_default'=>(bool)($w->is_default??false),'available_at'=>$w->available_at?->utc()->toIso8601String(),'verified_at'=>$w->verified_at?->utc()->toIso8601String(),'metadata'=>$w->metadata??new \stdClass(),'created_at'=>$w->created_at?->utc()->toIso8601String()];}
}