<?php

declare( strict_types=1 );

namespace Soft_Tehnica\Freya_Sync_Service\Services;

use WP_User;

final class AccountStore implements STDataStore
{

    private readonly WP_User|null $user;

    public function __construct()
    {
        $this->user = wp_get_current_user();
    }

    /**
     * @template T
     *
     * @return T|null
     */
    public function get( string $key ): mixed
    {
        if ( null === $this->user ) {
            return null;
        }

        $value = get_user_meta(
            $this->user->ID,
            $this->create_key( $key ),
            true
        );

        if ( $value === false || ( is_string( $value ) && strlen( $value ) === 0 ) ) {
            return null;
        }

        return $value;
    }

    /**
     * @template T
     *
     * @param T $value
     */
    public function put( string $key, $value ): void
    {
        if ( null === $this->user ) {
            return;
        }

        update_user_meta( $this->user->ID, $this->create_key( $key ), $value );
    }

    public function forget( string $key ): void
    {
        if ( null === $this->user ) {
            return;
        }

        delete_user_meta( $this->user->ID, $this->create_key( $key ) );
    }

    public function is_available(): bool
    {
        return null !== $this->user;
    }

    private function create_key( string $key ): string
    {
        return sprintf( 'freya-sync-service/%s', $key );
    }
}
