# Copyright (C) 2023 Cochise Ruhulessin
#
# All rights reserved. No warranty, explicit or implicit, provided. In
# no event shall the author(s) be liable for any claim or damages.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import secrets

import pytest
from google.cloud.datastore import Client

from cbra.ext.google import BaseDatastoreRepository


@pytest.mark.asyncio
async def test_put_autogenerated_and_retrieve(
    client: Client
):
    repo = BaseDatastoreRepository(client=client)
    e1 = repo.entity('Test')
    e1['foo'] = 'foo'
    k1 = await repo.put(e1)
    assert k1 == e1.key
    e2 = await repo.get_entity_by_key(e1.key)
    assert e1 == e2


@pytest.mark.asyncio
async def test_put_autogenerated_and_query(
    client: Client
):
    repo = BaseDatastoreRepository(client=client)
    e1 = repo.entity('Test')
    e1['foo'] = 'foo'
    k1 = await repo.put(e1)
    assert k1.id is not None
    q = repo.query(kind='Test')
    q.add_filter('foo', '=', 'foo')
    c = list(await repo.execute(q))
    assert k1 in [e.key for e in c]


@pytest.mark.asyncio
async def test_put_named_and_retrieve(
    client: Client
):
    repo = BaseDatastoreRepository(client=client)
    e1 = repo.entity('Test', secrets.token_urlsafe(32))
    e1['foo'] = 'foo'
    k1 = await repo.put(e1)
    assert k1 == e1.key
    e2 = await repo.get_entity_by_key(e1.key)
    assert e1 == e2


@pytest.mark.asyncio
async def test_put_named_and_query(
    client: Client
):
    repo = BaseDatastoreRepository(client=client)
    e1 = repo.entity('Test', secrets.token_urlsafe(32))
    e1['foo'] = 'foo'
    k1 = await repo.put(e1)
    q = repo.query(kind='Test')
    q.add_filter('foo', '=', 'foo')
    c = list(await repo.execute(q))
    assert k1 in [e.key for e in c]