<?php

namespace App\Models;

use App\Casts\AmountCast;
use App\Enumerations\InvoiceStatus;
use App\Enumerations\InvoiceType;
use App\Resources\EventResource;
use App\Scopes\InstancedModel;
use App\ValueObjects\Amount;
use Illuminate\Database\Eloquent\Relations\BelongsTo;


class CostUnitEstimate extends InstancedModel
{
    protected $fillable = [
        'tenant',
        'cost_unit_id',
        'type',
        'description',
        'flat_amount',
        'amount_by_user',
    ];

    protected $casts = [
        'flat_amount' =>  AmountCast::class,
        'amount_by_user' => AmountCast::class,
    ];

    public function costUnit() : BelongsTo{
        return $this->belongsTo(CostUnit::class);
    }

    public function invoiceType() : InvoiceType {
        return $this->belongsTo(InvoiceType::class, 'type', 'slug')->first();
    }

    public function calculateAmount() : ?Amount {
        switch (true) {
            case $this->flat_amount !== null:
                return $this->flat_amount;
            default:
                $event = $this->costUnit()->first()->event()?->first();
                if (null !== $event) {
                    $participants = $event->participants()->count();
                    $amount = clone($this->amount_by_user);
                    return $amount->multiply($participants);
                } else {
                    return $this->amount_by_user;
                }
        }
    }
}
