import pytest
from django.contrib import auth
from django.urls import reverse

from la_chariotte.order import models

from .utils import create_grouped_order

pytestmark = pytest.mark.django_db


class TestItemCreateView:
    def test_create_item(self, client_log):
        """A user that has created a grouped order adds an item to it."""
        grouped_order = create_grouped_order(
            days_before_delivery_date=5,
            days_before_deadline=2,
            name="gr order test",
            orga_user=auth.get_user(client_log),
        )
        create_item_view_url = reverse(
            "order:item_create",
            kwargs={
                "code": grouped_order.code,
            },
        )
        response = client_log.post(
            create_item_view_url, {"name": "titre item", "price": 2}
        )
        assert response.status_code == 302
        assert response.url == reverse(
            "order:manage_items",
            kwargs={
                "code": grouped_order.code,
            },
        )
        assert models.Item.objects.first().name == "titre item"
        response = client_log.get(response.url)
        assert "titre item" in response.content.decode()

    def test_create_item__anonymous_user(self, client, other_user):
        """
        A user that is not logged cannot create an item. They get a redirected to loginview.
        """
        grouped_order = create_grouped_order(
            days_before_delivery_date=5,
            days_before_deadline=2,
            name="gr order test",
            orga_user=other_user,
        )
        create_item_view_url = reverse(
            "order:item_create",
            kwargs={
                "code": grouped_order.code,
            },
        )
        response = client.post(create_item_view_url, {"name": "titre item"})
        assert response.status_code == 302
        assert (
            response.url == f"{reverse('accounts:login')}?next={create_item_view_url}"
        )

    def test_create_item__not_orga(self, client_log, other_user):
        """
        A user that is not orga cannot create an item. They get a 403 error.
        """
        grouped_order = create_grouped_order(
            days_before_delivery_date=5,
            days_before_deadline=2,
            name="gr order test",
            orga_user=other_user,
        )
        create_item_view_url = reverse(
            "order:item_create",
            kwargs={
                "code": grouped_order.code,
            },
        )
        response = client_log.post(create_item_view_url, {"name": "titre item"})
        assert response.status_code == 403
