<?php

namespace App\Domains\CostUnit\Actions\ChangeCostUnitTreasurers;

use App\Models\User;

class ChangeCostUnitTreasurersCommand {
    private ChangeCostUnitTreasurersRequest $request;

    public function __construct(ChangeCostUnitTreasurersRequest $request) {
        $this->request = $request;
    }

    public function execute() : ChangeCostUnitTreasurersResponse {
        $response = new ChangeCostUnitTreasurersResponse();

        try {
            $this->request->costUnit->resetTreasurers();

            foreach ($this->request->treasurers as $treasurer) {
                $this->request->costUnit->treasurers()->attach($treasurer);
            }

            $this->request->costUnit->save();
        } catch (\Throwable $th) {
            $response->success = false;
        }

        return $response;
    }
}
