<?php

declare(strict_types=1);

namespace App\Services;

use App\Repositories\UpdateDraftRepository;
use InvalidArgumentException;

final class UpdateDraftService
{
    public function __construct(
        private UpdateDraftRepository $repository
    ) {
    }

    public function create(array $data): int
    {
        $this->validate($data);

        $data['draft_uuid'] = $this->generateUuid();

        $data['code'] = $this->generateCode();

        $data['statut'] = 'draft';

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

    private function validate(array $data): void
    {
        if (trim((string) ($data['nom'] ?? '')) === '') {
            throw new InvalidArgumentException(
                'Le nom de la mise à jour est obligatoire.'
            );
        }

        if (trim((string) ($data['version_cible'] ?? '')) === '') {
            throw new InvalidArgumentException(
                'La version cible est obligatoire.'
            );
        }

        if (trim((string) ($data['version_source'] ?? '')) === '') {
            throw new InvalidArgumentException(
                'La version source est obligatoire.'
            );
        }
    }

    private function generateCode(): string
    {
        $year = date('Y');

        $sequence = sprintf('%06d', random_int(1, 999999));

        return sprintf(
            'UPD-%s-%s',
            $year,
            $sequence
        );
    }

    private function generateUuid(): string
    {
        $data = random_bytes(16);

        $data[6] = chr((ord($data[6]) & 0x0f) | 0x40);
        $data[8] = chr((ord($data[8]) & 0x3f) | 0x80);

        return vsprintf(
            '%s%s-%s-%s-%s-%s%s%s',
            str_split(bin2hex($data), 4)
        );
    }
}