<?php

namespace App\Classes\Modules\Accounts\Services;

use App\Classes\Exceptions\InternalServerErrorException;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Models\Company;
use App\Models\Role;
use App\Models\User;
use Carbon\Carbon;
use Tymon\JWTAuth\JWT;

class GeneratesAuthenticationToken {

    /** @var JWT */
    private $builder;


    /**
     * GeneratesAuthenticationToken constructor.
     * @param JWT $builder
     */
    public function __construct(JWT $builder) {
        $this->builder = $builder;
    }


    /**
     * @param User $user
     * @param bool $rememberUser
     * @return string
     */
    public function execute(User $user, bool $rememberUser = false): string {

        $this->builder->manager()->setBlacklistEnabled(false);

        // generate token for the customer
        $this->builder->factory()->setTTL(Carbon::now()->addDay()->timestamp);

        if ($rememberUser === true) {
            $this->builder->factory()->setTTL(Carbon::now()->addWeek()->timestamp);
        }

        // set the claim based on the object
        $this->setTokenClaims($user);

        return $this->builder->fromUser($user);
    }


    /**
     * @param User $user
     */
    private function setTokenClaims(User $user): void {

        $claims = [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'type' => $user->type,
            'status' => $user->status
        ];

        if($user->type === RoleTypes::USER) {

            /** @var Company $companyModule */
            $companyModule = $user->companyModule()->first();

            $claims = array_merge($claims, [
                'company_id' => $companyModule->company_id
            ]);
        }

        $this->builder->factory()->customClaims(['user' => $claims]);


        $this->builder->factory()->buildClaimsCollection();
    }
}
