<?php

namespace Fotogenic_AI;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

final class Auth_State_Store {
    private const TTL_SECONDS = 15 * MINUTE_IN_SECONDS;
    private const PREFIX = 'fotogenic_ai_auth_state_';

    public function store( int $user_id, string $state, array $payload ): void {
        if ( $user_id <= 0 || '' === $state ) {
            return;
        }

        set_transient( $this->build_key( $user_id, $state ), $payload, self::TTL_SECONDS );
    }

    public function consume( int $user_id, string $state ): ?array {
        if ( $user_id <= 0 || '' === $state ) {
            return null;
        }

        $key = $this->build_key( $user_id, $state );
        $payload = get_transient( $key );
        delete_transient( $key );

        return is_array( $payload ) ? $payload : null;
    }

    public function delete( int $user_id, string $state ): void {
        if ( $user_id <= 0 || '' === $state ) {
            return;
        }

        delete_transient( $this->build_key( $user_id, $state ) );
    }

    private function build_key( int $user_id, string $state ): string {
        return self::PREFIX . $user_id . '_' . substr( hash( 'sha256', $state ), 0, 24 );
    }
}
