<?php

namespace Database\Seeders;

use App\Models\Pouzivatel\Pouzivatel;
use App\Models\Pouzivatel\PouzivatelStavEnum;
use App\Models\Pracovisko\Pracovisko;
use Illuminate\Database\Seeder;
use Spatie\Permission\Exceptions\RoleDoesNotExist;
use Spatie\Permission\Models\Role;

/**
 * Class PouzivateliaDatabaseSeeder
 */
class PouzivateliaDatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $pek = Pracovisko::factory()->create([
            'kod' => '0000',
            'nazov' => 'S-EKA, spol. s r.o.',
        ]);

        $admin = [
            'login' => '0000-lukac',
            'meno' => 'Radoslav',
            'priezvisko' => 'Lukáč',
            'stav' => PouzivatelStavEnum::AKTIVNY,
        ];

        Pouzivatel::factory()
            ->make($admin)
            ->assignRole($this->getRole('admin'))
            ->pracovisko()
            ->associate($pek)
            ->save();
    }

    private function getRole(string $name): Role
    {
        try {
            $role = Role::findByName($name);
        } catch (RoleDoesNotExist $exception) {
            $role = Role::create(['name' => $name]);
        } finally {
            return $role;
        }
    }
}
