<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\Validator;
use App\Repositories\ClientRepository;
use App\Repositories\TypeClientRepository;

final class ClientService extends BaseService
{
    public function __construct(
        private readonly ClientRepository $clients = new ClientRepository(),
        private readonly TypeClientRepository $types = new TypeClientRepository(),
    ) {
    }

    public function listActive(): array
    {
        return $this->clients->allActive();
    }

    public function formData(?int $clientId = null): array
    {
        $client = $clientId ? $this->clients->find($clientId) : null;

        if ($clientId !== null && !$client) {
            throw new \RuntimeException('Client introuvable.');
        }

        return [
            'client' => $client ?? [
                'code_client' => $this->clients->nextCode(),
                'pays' => 'Maroc',
                'remise' => '0.00',
                'delai_paiement' => '0',
                'plafond_credit' => '0.00',
            ],
            'typesClients' => $this->types->allActive(),
        ];
    }

    public function create(array $data): int
    {
        if (empty($data['code_client'])) {
            $data['code_client'] = $this->clients->nextCode();
        }

        return $this->clients->create($data);
    }

    public function update(int $id, array $data): void
    {
        if ($id <= 0) {
            throw new \RuntimeException('Identifiant client invalide.');
        }
        $this->clients->update($id, $data);
    }

    public function deactivate(int $id): void
    {
        if ($id <= 0) {
            throw new \RuntimeException('Identifiant client invalide.');
        }
        $this->clients->deactivate($id);
    }

    public function findWithHistory(int $id): array
    {
        $client = $this->clients->find($id);
        if (!$client) {
            throw new \RuntimeException('Client introuvable.');
        }

        return [
            'client' => $client,
            'history' => $this->clients->history($id),
        ];
    }

    public function validator(array $data): Validator
    {
        return (new Validator())
            ->required('code_client', $data['code_client'] ?? '', 'Code client')
            ->required('raison_sociale', $data['raison_sociale'] ?? '', 'Raison sociale')
            ->email('email', $data['email'] ?? '', 'E-mail');
    }
}
