<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Models\KycDocument;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
final class KycDocumentController extends Controller {
 public function index(Request $r){return ApiResponse::success(KycDocument::where('merchant_id',$r->user()->id)->latest()->get()->map(fn($d)=>$this->resource($d))->values());}
 public function store(Request $r){$data=$r->validate(['type'=>['required','in:identity,business,proof_of_address,bank_statement,other'],'file'=>['required','file','mimes:jpg,jpeg,png,pdf','max:10240'],'metadata'=>['nullable','array']]);$file=$r->file('file');$path=$file->store('kyc/'.$r->user()->public_id,'local');$doc=KycDocument::create(['public_id'=>'kyc_'.Str::ulid(),'merchant_id'=>$r->user()->id,'type'=>$data['type'],'status'=>'submitted','file_path'=>$path,'original_filename'=>$file->getClientOriginalName(),'mime_type'=>$file->getMimeType(),'size_bytes'=>$file->getSize(),'metadata'=>$data['metadata']??[]]);$r->user()->forceFill(['kyc_status'=>'submitted','kyc_submitted_at'=>now()])->save();return ApiResponse::success($this->resource($doc),201);}
 public function show(Request $r,string $id){$doc=KycDocument::where('merchant_id',$r->user()->id)->where('public_id',$id)->first();if(!$doc)return ApiResponse::error('KYC_DOCUMENT_NOT_FOUND','The requested KYC document does not exist.',404);return ApiResponse::success($this->resource($doc));}
 private function resource(KycDocument $d):array{return ['id'=>$d->public_id,'type'=>$d->type,'status'=>$d->status,'original_filename'=>$d->original_filename,'mime_type'=>$d->mime_type,'size_bytes'=>(int)$d->size_bytes,'rejection_reason'=>$d->rejection_reason,'metadata'=>$d->metadata??new \stdClass(),'submitted_at'=>$d->created_at?->utc()->toIso8601String(),'reviewed_at'=>$d->reviewed_at?->utc()->toIso8601String()];}
}