<?php
declare(strict_types=1);
namespace App\Reference;
use InvalidArgumentException;
final class ReferenceService
{
    public function __construct(private readonly ReferenceRepository $repository = new ReferenceRepository()){}
    public function types(): array { return $this->repository->types(); }
    public function type(string $code): ?array { return $this->repository->typeByCode($code); }
    public function values(string $code,bool $includeArchived=false): array { $t=$this->type($code);return $t?$this->repository->values((int)$t['id'],$includeArchived):[]; }
    public function saveType(?int $id,array $input): int { $d=['code'=>$this->code($input['code']??''),'label'=>$this->label($input['label']??''),'description'=>trim((string)($input['description']??''))?:null,'icon'=>trim((string)($input['icon']??''))?:null,'display_order'=>(int)($input['display_order']??0),'is_active'=>isset($input['is_active'])?1:0,'fields_schema'=>$this->jsonOrNull((string)($input['fields_schema']??''))]; if($id){$this->repository->updateType($id,$d);return $id;} return $this->repository->createType($d); }
    public function saveValue(int $typeId,?int $id,array $input): int { $d=['code'=>$this->code($input['code']??''),'label'=>$this->label($input['label']??''),'description'=>trim((string)($input['description']??''))?:null,'icon'=>trim((string)($input['icon']??''))?:null,'color'=>trim((string)($input['color']??''))?:null,'display_order'=>(int)($input['display_order']??0),'is_active'=>isset($input['is_active'])?1:0,'metadata'=>$this->jsonOrNull((string)($input['metadata']??''))]; if($id){$this->repository->updateValue($id,$d);return $id;} return $this->repository->createValue($typeId,$d); }
    private function code(string $v): string {$v=strtolower(trim($v));$v=preg_replace('/[^a-z0-9._-]+/','_',$v)??'';$v=trim($v,'_');if($v==='')throw new InvalidArgumentException('Le code est obligatoire.');return $v;}
    private function label(string $v): string {$v=trim($v);if($v==='')throw new InvalidArgumentException('Le libellé est obligatoire.');return $v;}
    private function jsonOrNull(string $v): ?string {$v=trim($v);if($v==='')return null;json_decode($v,true);if(json_last_error()!==JSON_ERROR_NONE)throw new InvalidArgumentException('Le JSON est invalide : '.json_last_error_msg());return $v;}
}
