<?php

namespace Sitecake\Authentication\Identifier;

use Sitecake\Authentication\CredentialFileAwareTrait;
use Sitecake\Authentication\CredentialManager;
use Sitecake\Authentication\IdentifierInterface;

class CredentialFileIdentifier implements IdentifierInterface
{
    /**
     * Credential manager instance
     * @var CredentialManager
     */
    protected $credentialManager;

    /**
     * CredentialFileIdentifier constructor.
     *
     * @param CredentialManager $credentialManager
     */
    public function __construct(CredentialManager $credentialManager)
    {
        $this->credentialManager = $credentialManager;
    }

    /**
     * {@inheritdoc}
     *
     * Accepts a raw (plain-text) password in $credentials['password'].
     * Handles two stored formats:
     *   - Legacy: exactly 40 hex characters (SHA-1) — compares with hash_equals(),
     *     then upgrades storage to bcrypt on success.
     *   - Modern: bcrypt hash starting with "$2y$" — verified with password_verify().
     */
    public function identify(array $credentials)
    {
        if (!isset($credentials['password'])) {
            return false;
        }

        $storedCredentials = $this->credentialManager->getCredentials();
        $storedHash        = $storedCredentials['password'] ?? '';
        $rawPassword       = $credentials['password'];

        // Legacy SHA-1 format: exactly 40 lowercase hex characters
        if (preg_match('/^[0-9a-f]{40}$/', $storedHash)) {
            $submittedHash = sha1($rawPassword);
            if (hash_equals($storedHash, $submittedHash)) {
                // Upgrade stored hash to bcrypt on first successful login
                $this->credentialManager->upgradeCredentials($rawPassword);
                return true;
            }
            return false;
        }

        // Modern bcrypt format
        return password_verify($rawPassword, $storedHash);
    }
}
