<?php

namespace App\Tests\Auth;

use App\Auth\Entity\User;
use App\Tests\ApiTestCase;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

/**
 * POST /api/v1/user/change-password — authenticated password change.
 */
class ChangePasswordTest extends ApiTestCase
{
    private function userWithPassword(string $password): User
    {
        $user   = $this->createUser(['ROLE_DOCTOR']);
        $hasher = static::getContainer()->get(UserPasswordHasherInterface::class);
        $user->setPasswordHash($hasher->hashPassword($user, $password));
        $this->em->flush();
        return $user;
    }

    public function testChangesPasswordWithCorrectCurrent(): void
    {
        $user = $this->userWithPassword('oldpass12');

        $this->authJson('POST', '/api/v1/user/change-password', $user, [
            'current_password' => 'oldpass12',
            'new_password'     => 'newpass34',
        ]);
        self::assertSame(200, $this->responseCode());

        $hasher = static::getContainer()->get(UserPasswordHasherInterface::class);
        $this->em->clear();
        $reloaded = $this->em->getRepository(User::class)->find($user->getId());
        self::assertTrue($hasher->isPasswordValid($reloaded, 'newpass34'));
    }

    public function testRejectsWrongCurrentPassword(): void
    {
        $user = $this->userWithPassword('oldpass12');

        $this->authJson('POST', '/api/v1/user/change-password', $user, [
            'current_password' => 'wrongpass',
            'new_password'     => 'newpass34',
        ]);
        self::assertSame(422, $this->responseCode());
    }

    public function testRejectsShortNewPassword(): void
    {
        $user = $this->userWithPassword('oldpass12');

        $this->authJson('POST', '/api/v1/user/change-password', $user, [
            'current_password' => 'oldpass12',
            'new_password'     => 'short',
        ]);
        self::assertSame(422, $this->responseCode());
    }

    public function testRejectsSameAsCurrent(): void
    {
        $user = $this->userWithPassword('oldpass12');

        $this->authJson('POST', '/api/v1/user/change-password', $user, [
            'current_password' => 'oldpass12',
            'new_password'     => 'oldpass12',
        ]);
        self::assertSame(422, $this->responseCode());
    }
}
