<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Devis;
use App\Repositories\ArticleRepository;

final class DevisService extends BaseService
{
    public function __construct(private readonly Devis $devis = new Devis())
    {
    }

    public function list(): array
    {
        return $this->devis->all();
    }

    public function createFormData(): array
    {
        return [
            'mode' => 'create',
            'numero' => $this->devis->nextNumber(),
            'clients' => $this->devis->clientsForSelect(),
            'articles' => (new ArticleRepository())->pickerActive(),
            'today' => date('Y-m-d'),
            'validite' => date('Y-m-d', strtotime('+30 days')),
            'devis' => null,
            'lignes' => [],
            'errors' => [],
        ];
    }

    public function editFormData(int $id): array
    {
        $data = $this->findWithLines($id);
        return [
            'mode' => 'edit',
            'numero' => (string)$data['devis']['numero'],
            'clients' => $this->devis->clientsForSelect(),
            'articles' => (new ArticleRepository())->pickerActive(),
            'today' => (string)$data['devis']['date_devis'],
            'validite' => (string)($data['devis']['validite'] ?? ''),
            'devis' => $data['devis'],
            'lignes' => $data['lignes'],
            'errors' => [],
        ];
    }

    public function create(array $data): int
    {
        if ((int)($data['client_id'] ?? 0) <= 0) {
            throw new \RuntimeException('Veuillez sélectionner un client.');
        }
        return $this->devis->create($data);
    }

    public function update(int $id, array $data): void
    {
        if ($id <= 0) {
            throw new \RuntimeException('Identifiant devis invalide.');
        }
        if ((int)($data['client_id'] ?? 0) <= 0) {
            throw new \RuntimeException('Veuillez sélectionner un client.');
        }
        $this->devis->update($id, $data);
    }

    public function duplicate(int $id): int
    {
        if ($id <= 0) {
            throw new \RuntimeException('Identifiant devis invalide.');
        }
        return $this->devis->duplicate($id);
    }

    public function findWithLines(int $id): array
    {
        $devis = $this->devis->find($id);
        if (!$devis) {
            throw new \RuntimeException('Devis introuvable.');
        }
        return ['devis' => $devis, 'lignes' => $this->devis->lines($id)];
    }
}
