<?php

namespace App\DataFixtures;

use App\Entity\Company;
use App\Entity\User;
use App\Enums\CaseLevel;
use App\Enums\RateType;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class UserFixture extends Fixture
{
    public function __construct(
        private readonly UserPasswordHasherInterface $userPasswordHasher,
    ) {

    }

    public function load(ObjectManager $manager): void
    {
        if(!$_ENV['CREATE_USERS']) {
            return;
        }
        $comp = $manager->getRepository(Company::class)->findOneBy(['name' => 'Counseling Partners, LLC']);
        $gen = \Faker\Factory::create();
        for ($x = 0; $x < $_ENV['CREATE_USERS']; $x++) {
            $user = new User();
            $name = $gen->firstName().' '.$gen->lastName();
            $username = strtolower(str_replace(' ', '.', $name));
            $cw = true;
            $cm = $gen->boolean();
            $t = $gen->boolean();
            $su = $gen->boolean();
            $roles = ['ROLE_USER', 'ROLE_CASE_WORKER'];
            if ($cm) {
                $roles[] = 'ROLE_CASE_MANAGER';
            }
            if ($t) {
                $roles[] = 'ROLE_THERAPIST';
            }
            if ($su) {
                $roles[] = 'ROLE_ADMIN';
            }

            $user->setName($name)
                 ->setUsername($username)
                 ->setEmail($username.'@counselingpartnersllc.com')
                 ->setCaseManager($cm)
                 ->setCaseWorker($cw)
                 ->setTherapist($t)
                 ->setSu($su)
                 ->setRoles($roles)
                 ->setRateType($gen->randomElement(RateType::class))
                 ->setRate($gen->numberBetween(0, 100))
                 ->setLevel($gen->randomElement(CaseLevel::class))
                 ->setCompany($comp)
                 ->setPassword($this->userPasswordHasher->hashPassword($user, 'password'))
            ;

            print "Creating user $name - $username".PHP_EOL;

            $manager->persist($user);
        }

        $manager->flush();
    }
}
