<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Tests\User;

use CpCreation\VitiCore\Product\Model\ProductPriceGroup;
use CpCreation\VitiCore\User\ImportedClientGroupAssigner;
use CpCreation\VitiCore\User\Model\ImportedClientGroup;
use CpCreation\VitiCore\User\Model\User;
use CpCreation\VitiCore\User\Repository\ImportedClientGroupRepository;
use PHPUnit\Framework\TestCase;

final class ImportedClientGroupAssignerTest extends TestCase
{
    public function testItAssignsTheImportedGroupWhenTheCustomerRegisters(): void
    {
        $group = new ProductPriceGroup();
        $group->setName('Club');
        $importedClient = new ImportedClientGroup('client@example.com', $group);

        $repository = $this->createMock(ImportedClientGroupRepository::class);
        $repository
            ->expects(self::once())
            ->method('findOneByEmail')
            ->with('client@example.com')
            ->willReturn($importedClient);

        $user = new User();
        $user->setEmail('client@example.com');

        $assigned = new ImportedClientGroupAssigner($repository)->assignTo($user);

        self::assertTrue($assigned);
        self::assertSame($group, $user->getGroup());
    }

    public function testItKeepsTheUserWithoutAGroupWhenTheEmailWasNotImported(): void
    {
        $repository = $this->createMock(ImportedClientGroupRepository::class);
        $repository->method('findOneByEmail')->willReturn(null);

        $user = new User();
        $user->setEmail('inconnu@example.com');

        $assigned = new ImportedClientGroupAssigner($repository)->assignTo($user);

        self::assertFalse($assigned);
        self::assertNull($user->getGroup());
    }

    public function testItDoesNotAssignTheGroupWhenApplicationWasDisabledAfterImport(): void
    {
        $group = new ProductPriceGroup();
        $group->setName('Club');
        $importedClient = new ImportedClientGroup('client@example.com', $group);
        $importedClient->setApplyOnRegistration(false);

        $repository = $this->createMock(ImportedClientGroupRepository::class);
        $repository->method('findOneByEmail')->willReturn($importedClient);

        $user = new User();
        $user->setEmail('client@example.com');

        $assigned = new ImportedClientGroupAssigner($repository)->assignTo($user);

        self::assertFalse($assigned);
        self::assertNull($user->getGroup());
    }
}
