<?php
declare(strict_types=1);

namespace App\Users;

use PDO;

final class TrustService
{
    public const TYPES = ['member','editorial','system'];

    public function __construct(private readonly ?PDO $pdo = null) {}

    /** @param array<string,mixed> $user */
    public static function accountType(array $user): string
    {
        $type = strtolower(trim((string) ($user['account_type'] ?? 'member')));
        return in_array($type, self::TYPES, true) ? $type : 'member';
    }

    /** @param array<string,mixed> $user */
    public static function canLogin(array $user): bool
    {
        return strtolower(trim((string) ($user['status'] ?? ''))) === 'active'
            && empty($user['login_disabled'])
            && self::accountType($user) === 'member';
    }

    /** @return array<string,mixed>|null */
    public function user(int $userId): ?array
    {
        if (!$this->pdo || $userId <= 0) return null;
        $stmt=$this->pdo->prepare('SELECT id,role,status,account_type,trust_level,login_disabled,email_verified_at,created_at FROM users WHERE id=:id LIMIT 1');
        $stmt->execute(['id'=>$userId]);$row=$stmt->fetch(PDO::FETCH_ASSOC);return is_array($row)?$row:null;
    }

    /** @param array<string,mixed> $user */
    public static function context(array $user): array
    {
        $created=strtotime((string)($user['created_at']??''));
        $ageHours=$created===false?0:max(0,(int)floor((time()-$created)/3600));
        return [
            'account_type'=>self::accountType($user),
            'trust_level'=>max(0,min(5,(int)($user['trust_level']??0))),
            'account_age_hours'=>$ageHours,
            'email_verified'=>!empty($user['email_verified_at']),
            'login_disabled'=>!empty($user['login_disabled']),
        ];
    }
}
