<?php

declare(strict_types=1);

namespace SbpJm\FlarumMSTeamsWebhook\Support;

use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\User\User;

class TargetResolver
{
    public function __construct(protected SettingsRepositoryInterface $settings)
    {
    }

    public function resolve(User $user): ?string
    {
        $strategy = trim((string) $this->settings->get('sbp-jm-msteams-webhook.user_lookup_strategy', 'email'));

        return match ($strategy) {
            'email' => $this->clean($user->email),
            'upn' => $this->resolveUpn($user),
            'preference' => $this->clean($user->getPreference((string) $this->settings->get('sbp-jm-msteams-webhook.user_preference_key', 'sbp-jm-msteams-webhook.target'))),
            default => $this->clean($user->email),
        };
    }

    protected function resolveUpn(User $user): ?string
    {
        $preferenceKey = (string) $this->settings->get('sbp-jm-msteams-webhook.upn_preference_key', 'sbp-jm-msteams-webhook.upn');
        $upn = $this->clean($user->getPreference($preferenceKey));

        if ($upn !== null) {
            return $upn;
        }

        return $this->clean($user->email);
    }

    protected function clean(mixed $value): ?string
    {
        if (!is_string($value)) {
            return null;
        }

        $value = trim($value);

        return $value === '' ? null : $value;
    }
}
