<?php

namespace App\Domains\Budget\Actions\CreateEstimate;

use App\Models\CostUnitEstimate;

class CreateEstimateAction {
    private CreateEstimateResponse $response;

   public function __construct(private CreateEstimateRequest $request) {
    }

    public function execute(): CreateEstimateResponse {
        $this->response = new CreateEstimateResponse();

        $amount = [];
        switch ($this->request->amountType) {
            case 'flat':
                $amount['flat_amount'] = $this->request->amount;
                break;
            case 'per_person':
                $amount['amount_by_user'] = $this->request->amount;
                break;
        }

        if ($this->request->estimateId === 0) {
            $estimate = CostUnitEstimate::create(array_merge([
                'tenant' => app('tenant')->slug,
                'cost_unit_id' => $this->request->costUnit->id,
                'type' => $this->request->estimateType,
                'description' => $this->request->description,
            ], $amount));
        } else {
            $estimate = CostUnitEstimate::find($this->request->estimateId);
            $estimate->update(array_merge([
                'tenant' => app('tenant')->slug,
                'cost_unit_id' => $this->request->costUnit->id,
                'type' => $this->request->estimateType,
                'description' => $this->request->description,
            ], $amount));
        }

        if ($estimate !== null) {
            $this->response->estimateId = $estimate->id;
            $this->response->success = true;
        }

        return $this->response;
    }
}
