<?php

namespace App\Classes\Modules\Banks\Services;

use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\Modules\Banks\DataTransferObjects\BankObject;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Models\Bank;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class CreatesOrUpdateBank extends AbstractUpdateRecord
{
    /**
     * @param BankObject $object
     * @return \Illuminate\Database\Eloquent\Model
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute(BankObject $object)
    {
        $user = Auth::user(); /** @var User $user */
        $attributes = [
            'company_id' => $object->getCompanyId(),
            'account_no' => $object->getAccountNo(),
            'reference' => $object->getReference(),
            'bank_name' => $object->getBankName(),
            'holder_name' => $object->getHolderName(),
            'bank_branch' => $object->getBankBranch(),
            'type' => $object->getType(),
            'country_id' => $object->getCountryId(),
            'created_by' => Auth::id(),
            'creator_type' => in_array($user->type, RoleTypes::ADMIN_ROLES) ? RoleTypes::ADMIN : RoleTypes::USER,
        ];

        $values = [
            'swift' => $object->getSwift(),
            'snap' => $object->getSnap(),
        ];

        $model = Bank::updateOrCreate($attributes, $values); //Bank::firstOrCreate($attributes, $values);

        return $model;
    }
}
