<?php

namespace App\Repositories;

use App\Models\CostUnit;
use App\Models\CostUnitEstimate;
use App\ValueObjects\Amount;

class EstimatesRepository {
    public function getEstimates(CostUnit $costUnit, string $estimateType) : array {
        $return = [];
        foreach ($costUnit->estimates()->where('type', $estimateType)->get() as $estimate) {
            $return[] = $estimate->toResource()->toArray(request());
        }

        return $return;
    }

    public function getById(int $estimateId, bool $accessCheck = true) : ?CostUnitEstimate {
        $estimate = CostUnitEstimate::find($estimateId);
        if ($estimate === null) {
            return null;
        }

        if ($accessCheck) {
            $costUnitRepository = new CostUnitRepository();
            if (null ===  $costUnitRepository->getById($estimate->cost_unit_id)) {
                return null;
            }
        }

        return $estimate;
    }

    public function getTotalAmount(CostUnit $costUnit, string $estimateType) : Amount {
        $total = new Amount(0, 'Euro');
        foreach ($costUnit->estimates()->where('type', $estimateType)->get() as $estimate) {
            $total->addAmount($estimate->calculateAmount());
        }

        return $total;
    }

}
