<?php

declare(strict_types=1);

namespace App\Services;

use App\Repositories\EncaissementRepository;
use App\Models\Facture;

final class FactureService extends BaseService
{
    public function __construct(
        private readonly Facture $factures = new Facture(),
        private readonly EncaissementRepository $encaissements = new EncaissementRepository(),
    ) {
    }

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

    public function createFromBonLivraison(int $bonLivraisonId): int
    {
        if ($bonLivraisonId <= 0) {
            throw new \RuntimeException('Identifiant bon de livraison invalide.');
        }
        return $this->factures->createFromBonLivraison($bonLivraisonId);
    }


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

    public function findWithDetails(int $id): array
    {
        $facture = $this->factures->find($id);
        if (!$facture) {
            throw new \RuntimeException('Facture introuvable.');
        }

        return [
            'facture' => $facture,
            'lignes' => $this->factures->lines($id),
            'encaissements' => $this->encaissements->forFacture($id),
        ];
    }
}
