<?php

declare(strict_types=1);

namespace App\Models;

/**
 * Authenticated Karvi Partner user stored in session after API login.
 */
final class User
{
    public function __construct(
        public readonly string $token,
        public readonly string $tokenType,
        public readonly string $userType,
        public readonly int $userId,
        public readonly string $loginId,
        public readonly ?string $name = null,
        public readonly ?string $email = null,
        public readonly ?string $loggedInAt = null,
    ) {
    }

    public static function fromApiResponse(array $response): self
    {
        return new self(
            token: (string)($response['token'] ?? ''),
            tokenType: (string)($response['token_type'] ?? 'Bearer'),
            userType: (string)($response['user_type'] ?? ''),
            userId: (int)($response['user_id'] ?? 0),
            loginId: (string)($response['login_id'] ?? ''),
            name: isset($response['name']) ? (string)$response['name'] : null,
            email: isset($response['email']) ? (string)$response['email'] : null,
            loggedInAt: date('Y-m-d H:i:s'),
        );
    }

    public function toSessionArray(): array
    {
        return [
            'token' => $this->token,
            'token_type' => $this->tokenType,
            'user_type' => $this->userType,
            'user_id' => $this->userId,
            'login_id' => $this->loginId,
            'name' => $this->name,
            'email' => $this->email,
            'logged_in_at' => $this->loggedInAt,
        ];
    }

    public static function fromSessionArray(array $data): ?self
    {
        $token = trim((string)($data['token'] ?? ''));
        if ($token === '') {
            return null;
        }

        return new self(
            token: $token,
            tokenType: (string)($data['token_type'] ?? 'Bearer'),
            userType: (string)($data['user_type'] ?? ''),
            userId: (int)($data['user_id'] ?? 0),
            loginId: (string)($data['login_id'] ?? ''),
            name: isset($data['name']) ? (string)$data['name'] : null,
            email: isset($data['email']) ? (string)$data['email'] : null,
            loggedInAt: isset($data['logged_in_at']) ? (string)$data['logged_in_at'] : null,
        );
    }
}
