"""
Contract Tests: Cart API

Endpoint: /productos/api/v1/cart/
App: productos

Related Tickets:
- VET-538: Test creación de cart vinculado al petowner
- VET-535: Establecer y definir test para las apis vinculadas al procesos de solicitar turno general

Context: In the turnero general flow (Step 2), a cart is created for the guest petowner.
The cart holds selected services and calculates price summary (subtotals, discounts, total).

TBD: CartViewSet needs pagination/filtering - list endpoint hangs on large dataset.
     See productos/api/v1/viewsets.py:93
"""

import pytest
from ..base import ContractTestCase
from ..endpoints import Endpoints
from ..helpers import sample_pet_owner, unique_email


class TestCartCreate(ContractTestCase):
    """POST /productos/api/v1/cart/

    VET-538: Tests for cart creation linked to petowner (Step 2 of turnero flow)
    """

    def _create_petowner(self):
        """Helper to create a pet owner"""
        data = sample_pet_owner(unique_email("cart_owner"))
        response = self.post(Endpoints.PET_OWNERS, data)
        return response.data["id"]

    def test_create_cart_for_petowner(self):
        """
        Creating a cart returns 201 and links to petowner.

        Request (from production turnero):
            POST /productos/api/v1/cart/
            {
                "petowner": 12345,
                "services": []
            }

        Response (201):
            {
                "id": 789,
                "petowner": 12345,
                "veterinarian": null,
                "items": [],
                "resume": [
                    {"concept": "SUBTOTAL", "amount": "0.00", "order": 1},
                    {"concept": "COSTO_SERVICIO", "amount": "0.00", "order": 2},
                    {"concept": "DESCUENTO", "amount": "0.00", "order": 3},
                    {"concept": "TOTAL", "amount": "0.00", "order": 4},
                    {"concept": "ADELANTO", "amount": "0.00", "order": 5}
                ],
                "extra_details": "",
                "pets": [],
                "pet_reasons": []
            }
        """
        owner_id = self._create_petowner()
        data = {
            "petowner": owner_id,
            "services": []
        }

        response = self.post(Endpoints.CART, data)

        self.assert_status(response, 201)
        self.assert_has_fields(response.data, "id", "petowner", "items")
        self.assertEqual(response.data["petowner"], owner_id)

    def test_cart_has_price_summary_fields(self):
        """
        Cart response includes price summary fields.

        These fields are critical for turnero flow - user needs to see:
        - resume: array with price breakdown (SUBTOTAL, DESCUENTO, TOTAL, etc)
        - items: cart items with individual pricing
        """
        owner_id = self._create_petowner()
        data = {"petowner": owner_id, "services": []}

        response = self.post(Endpoints.CART, data)

        self.assert_status(response, 201)
        # Price fields should exist (may be 0 for empty cart)
        self.assert_has_fields(response.data, "resume", "items")

    def test_empty_cart_has_zero_totals(self):
        """
        Empty cart (no services) has zero price totals.

        Validates initial state before services are added.
        """
        owner_id = self._create_petowner()
        data = {"petowner": owner_id, "services": []}

        response = self.post(Endpoints.CART, data)

        self.assert_status(response, 201)
        # Empty cart should have resume with zero amounts
        self.assertIn("resume", response.data)
        # Find TOTAL concept in resume
        total_item = next((item for item in response.data["resume"] if item["concept"] == "TOTAL"), None)
        self.assertIsNotNone(total_item)
        self.assertEqual(total_item["amount"], "0.00")


class TestCartRetrieve(ContractTestCase):
    """GET /productos/api/v1/cart/{id}/"""

    def _create_petowner_with_cart(self):
        """Helper to create petowner and cart"""
        owner_data = sample_pet_owner(unique_email("cart_owner"))
        owner_response = self.post(Endpoints.PET_OWNERS, owner_data)
        owner_id = owner_response.data["id"]

        cart_data = {"petowner": owner_id, "services": []}
        cart_response = self.post(Endpoints.CART, cart_data)
        return cart_response.data["id"]

    def test_get_cart_by_id_returns_200(self):
        """GET cart by ID returns cart details"""
        cart_id = self._create_petowner_with_cart()

        response = self.get(Endpoints.CART_DETAIL.format(id=cart_id))

        self.assert_status(response, 200)
        self.assertEqual(response.data["id"], cart_id)

    def test_detail_returns_404_for_nonexistent(self):
        """GET /cart/{id}/ returns 404 for non-existent cart"""
        response = self.get(Endpoints.CART_DETAIL.format(id=999999))
        self.assert_status(response, 404)


class TestCartList(ContractTestCase):
    """GET /productos/api/v1/cart/"""

    @pytest.mark.skip(reason="TBD: Cart list hangs - needs pagination/filtering. Checking if dead code.")
    def test_list_returns_200(self):
        """GET /cart/ returns 200"""
        response = self.get(Endpoints.CART)
        self.assert_status(response, 200)
