<?php

namespace App\Tests\Service;

use App\Service\UnsubscribeManager;
use PHPUnit\Framework\TestCase;

class UnsubscribeManagerTest extends TestCase
{
    private string $tempDir;
    private UnsubscribeManager $manager;

    protected function setUp(): void
    {
        $this->tempDir = sys_get_temp_dir() . '/unsubscribe_test_' . uniqid();
        mkdir($this->tempDir);
        $this->manager = new UnsubscribeManager($this->tempDir, 'secret');
    }

    protected function tearDown(): void
    {
        if (file_exists($this->tempDir . '/var/unsubscribed.json')) {
            unlink($this->tempDir . '/var/unsubscribed.json');
        }
        if (is_dir($this->tempDir . '/var')) {
            rmdir($this->tempDir . '/var');
        }
        rmdir($this->tempDir);
    }

    public function testGenerateToken(): void
    {
        $email = 'test@example.com';
        $token = $this->manager->generateToken($email);
        $this->assertNotEmpty($token);
        $this->assertTrue($this->manager->isValidToken($email, $token));
        $this->assertFalse($this->manager->isValidToken($email, 'wrong_token'));
    }

    public function testUnsubscribe(): void
    {
        $email = 'test@example.com';
        $this->assertFalse($this->manager->isUnsubscribed($email));

        $this->manager->unsubscribe($email);
        $this->assertTrue($this->manager->isUnsubscribed($email));

        // Re-unsubscribe should not duplicate or fail
        $this->manager->unsubscribe($email);
        $this->assertTrue($this->manager->isUnsubscribed($email));
    }

    public function testLoadEmptyHashes(): void
    {
        $this->assertFalse($this->manager->isUnsubscribed('none@example.com'));
    }
}
