<?php

namespace Database\Seeders\Companies;

use App\Imports\CompaniesImport;
use App\Models\Companies\Company;
use App\Models\Companies\CompanyMemberRank;
use App\Models\Companies\Department;
use App\Models\User;
use App\Services\DaDataService;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class CompaniesTableSeeder extends Seeder {
    public array $companies = [
        '7736151499' => [
            'is_main' => 1,
            'members' => [
                'test1@testnir.ru' => ['name' => 'Иванов Иван Иванович', 'position' => 'Генеральный директор', 'rank' => CompanyMemberRank::CHIEF],
                'test2@testnir.ru' => ['name' => 'Петров Петр Петрович', 'position' => 'Заместитель генерального директора', 'rank' => CompanyMemberRank::VICE]
            ]
        ]
    ];
    public string $import = '';

    public function run() {
        collect($this->companies)->each(function($data, $inn) {
            $company = Company::query()->firstOrCreate(['inn' => $inn]);
            (new DaDataService($inn))->saveToCompany($company);
            $company->update(collect($data)->except('departments', 'members', 'phone', 'email')->all());
            $company->setEmail($data['email'] ?? null);
            $company->setPhone($data['phone'] ?? null);
            $this->syncMembers($company->rootDepartment, $data['members'] ?? []);
            $this->syncDepartments($company->rootDepartment, $data['departments'] ?? []);
        });
        if ($this->import && Storage::exists($this->import)) Excel::import(new CompaniesImport(), Storage::path($this->import));
    }

    public function syncDepartments(Department $parent, $data) {
        collect($data)->each(function($data, $name) use($parent) {
            if ($department = $parent->addChildren($name, $data['title'] ?? null)) {
                $this->syncMembers($department, $data['members'] ?? []);
                $this->syncDepartments($department, $data['departments'] ?? []);
            }
        });
    }

    public function syncMembers(Department $department, $data) {
        collect($data)->each(function($data, $email) use($department) {
            $user = User::getByData(['email' => $email, 'name' => $data['name'] ?? '']);
            $member = $department->addMember($user, $data['position'] ?? '');
            $member->update(['rank' => $data['rank'] ?? CompanyMemberRank::EMPLOYEE]);
        });
    }
}
