from pyidentity.abc.data_protector import IDataProtector, IPersonalDataProtector
from pyidentity.encryption._backends import AESBackend
from pyidentity.utils import ensure_str

__all__ = ("PersonalDataProtector",)


class PersonalDataProtector(IPersonalDataProtector):
    def __init__(
        self,
        key: str | bytes | None = None,
        key_salt: str | bytes = b"personal.protector",
        backend: IDataProtector | None = None,
    ) -> None:
        if key is None and backend is None:
            raise ValueError("Either key or backend must be provided")
        if backend is not None:
            self._backend = backend
        if backend is None and key is not None:
            self._backend = AESBackend(key, key_salt)

    def protect(self, data: str | bytes) -> str:
        return ensure_str(self._backend.encrypt(data))

    def unprotect(self, data: str | bytes) -> str:
        return ensure_str(self._backend.decrypt(data))
