<?php

declare(strict_types=1);

namespace App\Models;

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

    public static function fromApiResponse(array $response): self
    {
        if (empty($response['token'])) {
            throw new \InvalidArgumentException('API login response did not include a token.');
        }

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

    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' => date('Y-m-d H:i:s'),
        ];
    }

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

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