<?php

namespace Database\Seeders;

use App\Classes\Modules\Companies\DataTransferObjects\EmploymentObject;
use App\Classes\Modules\Companies\Processors\AssignEmployeeProcessor;
use App\Models\CompanyConnection;
use App\Models\Exchange\Company as ExchangeCompany;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CompanyEmployeesTableSeeder extends Seeder
{

    /** @var AssignEmployeeProcessor */
    private $assignEmployeeProcessor;

    /**
     * CompanyEmployeesTableSeeder constructor.
     * @param AssignEmployeeProcessor $assignEmployeeProcessor
     */
    public function __construct(AssignEmployeeProcessor $assignEmployeeProcessor)
    {
        $this->assignEmployeeProcessor = $assignEmployeeProcessor;
    }


    /**
     * Run the database seeds.
     *
     * @return void
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function run()
    {
        DB::beginTransaction();
        foreach(ExchangeCompany::all() as $company) {

            if($connection = CompanyConnection::where('invitee_reference', $company->reference)->first()){

                $companyModule = $connection->invitee;

                if($companyModule->employees()->exists()) {
                    continue;
                }

                $exchangeUser = $company->employees()->first();

                if(User::where('email', '=', $exchangeUser->email)->count()){
                    continue;
                }

                $user = new User();
                $user->name = $exchangeUser->name;
                $user->email = $exchangeUser->email;
                $user->password = $exchangeUser->password;
                $user->type = $exchangeUser->type;
                $user->status = $exchangeUser->status;

                $user->save();

                $Object = new EmploymentObject($companyModule, $user);

                $this->assignEmployeeProcessor->execute($Object);
            }

        }
        DB::commit();


    }

}
