import pytest

from conftest import assert_data
from program.models import LinkType
from program.tests.factories import ProfileFactory

pytestmark = pytest.mark.django_db


def url(profile=None) -> str:
    return f"/api/v1/profiles/{profile.id}/" if profile else "/api/v1/profiles/"


def profile_data(image=None, link_type: LinkType = None) -> dict[str, str | int]:
    data = {
        "biography": "BIOGRAPHY",
        "email": "host@aura.radio",
        "name": "NAME",
        "owner_ids": [1],
    }

    if image:
        data["image_id"] = image.id

    if link_type:
        data["links"] = [{"type_id": link_type.id, "url": "https://aura.radio"}]

    return data


def test_create_profile(admin_api_client):
    data = profile_data()

    response = admin_api_client.post(url(), data=data)

    assert response.status_code == 201

    assert_data(response, data)


def test_create_profile_with_links(admin_api_client, link_type):
    data = profile_data(link_type=link_type)

    response = admin_api_client.post(url(), data=data, format="json")

    assert response.status_code == 201

    assert_data(response, data)


def test_create_profile_forbidden_for_common_user(common_api_client1):
    data = profile_data()

    response = common_api_client1.post(url(), data=data)

    assert response.status_code == 403


def test_delete_profile(admin_api_client, profile):
    response = admin_api_client.delete(url(profile))

    assert response.status_code == 204


def test_delete_profile_forbidden_for_common_user(common_api_client1, profile):
    response = common_api_client1.delete(url(profile))

    assert response.status_code == 403


def test_list_profile(admin_api_client):
    HOSTS = 3
    ProfileFactory.create_batch(size=HOSTS)

    response = admin_api_client.get(url())

    assert len(response.data) == HOSTS


def test_retrieve_profile(api_client, profile):
    response = api_client.get(url(profile))

    assert response.status_code == 200


def test_update_profile(admin_api_client, profile, image):
    update = profile_data(image)
    update["is_active"] = False

    response = admin_api_client.put(url(profile), data=update)

    assert response.status_code == 200

    assert_data(response, update)


def test_update_host_profile(admin_api_client, profile, link_type):
    update = profile_data(link_type=link_type)

    response = admin_api_client.patch(url(profile), data=update, format="json")

    assert response.status_code == 200

    assert_data(response, update)


def test_update_profile_forbidden_for_common_user(common_api_client1, profile):
    update = profile_data()

    response = common_api_client1.put(url(profile), data=update)

    assert response.status_code == 403


def test_redacted_fields_for_unauthenticated_requests(api_client, profile):
    response = api_client.get(url(profile))
    data = response.json()

    assert response.status_code == 200

    assert "email" not in data
    assert "cba" not in data