"""Smoke tests for the Floating-AI Auto Product Create flow.

Covers:
  - GET  /api/items/check-duplicate    (barcode + fuzzy name probe)
  - POST /api/items                    (409 on barcode conflict)
  - POST /api/items                    (round-trip with full AI-detected payload)
"""
import time

import pytest

from conftest import BASE_URL  # type: ignore[import-not-found]


def _unique_barcode():
    return f"AUTOTEST{int(time.time()*1000)}"


@pytest.mark.critical
class TestAutoProductCreate:
    def test_check_duplicate_endpoint_exists(self, admin_session, default_company_id):
        r = admin_session.get(
            f"{BASE_URL}/api/items/check-duplicate",
            params={"company_id": default_company_id, "name": "definitely-not-an-item-xyz"},
            timeout=20,
        )
        assert r.status_code == 200, r.text
        body = r.json()
        assert "barcode_match" in body
        assert "name_match" in body
        # No name like that exists
        assert body["barcode_match"] is None

    def test_check_duplicate_finds_known_item(self, admin_session, default_company_id):
        bc = _unique_barcode()
        # Seed one item
        seed = admin_session.post(
            f"{BASE_URL}/api/items",
            params={"company_id": default_company_id},
            json={
                "name": f"Auto Test Item {bc}",
                "barcode": bc,
                "base_unit": "PCS", "unit": "PCS",
                "category": "Grocery", "gst_rate": 18,
                "mrp": 100.0, "sale_price": 90.0,
                "opening_stock": 10,
            },
            timeout=20,
        )
        assert seed.status_code == 200, seed.text

        # Probe by barcode
        r = admin_session.get(
            f"{BASE_URL}/api/items/check-duplicate",
            params={"company_id": default_company_id, "barcode": bc},
            timeout=20,
        )
        assert r.status_code == 200
        body = r.json()
        assert body["barcode_match"] is not None
        assert body["barcode_match"]["name"].endswith(bc)

    def test_post_items_409_on_duplicate_barcode(self, admin_session, default_company_id):
        bc = _unique_barcode()
        # Seed
        first = admin_session.post(
            f"{BASE_URL}/api/items",
            params={"company_id": default_company_id},
            json={"name": f"First {bc}", "barcode": bc, "base_unit": "PCS", "unit": "PCS"},
            timeout=20,
        )
        assert first.status_code == 200

        # Try to create another with the same barcode → 409
        dup = admin_session.post(
            f"{BASE_URL}/api/items",
            params={"company_id": default_company_id},
            json={"name": f"Second {bc}", "barcode": bc, "base_unit": "PCS", "unit": "PCS"},
            timeout=20,
        )
        assert dup.status_code == 409, dup.text
        detail = dup.json().get("detail") or {}
        assert detail.get("duplicate_kind") == "barcode"
        assert "existing_name" in detail
        assert "current_stock" in detail

    def test_full_ai_detected_payload_roundtrips(self, admin_session, default_company_id):
        """The AI Auto Product Create dialog assembles this exact payload — confirm
        the POST /api/items contract accepts all of it and the resulting GET round-trips."""
        bc = _unique_barcode()
        payload = {
            "name": f"AI Scanned {bc}",
            "code": bc, "barcode": bc, "hsn": "8443",
            "base_unit": "PCS", "unit": "PCS",
            "category": "Personal Care",
            "gst_rate": 18,
            "mrp": 250.0, "sale_price": 225.0, "purchase_price": 150.0,
            "opening_stock": 5, "current_stock": 5,
            "low_stock_threshold": 2,
            # tiny base64 image to exercise the photo_url path
            "photo_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
            "allow_decimal": True,
        }
        r = admin_session.post(
            f"{BASE_URL}/api/items",
            params={"company_id": default_company_id},
            json=payload,
            timeout=30,
        )
        assert r.status_code == 200, r.text
        created = r.json()
        assert created["name"].endswith(bc)
        assert created["barcode"] == bc
        assert created["mrp"] == 250.0
        assert created["photo_url"].startswith("data:image/png;base64,")
        assert created["current_stock"] == 5

    def test_unauthenticated_blocked(self):
        import requests
        anon = requests.Session()
        r = anon.get(f"{BASE_URL}/api/items/check-duplicate", params={"company_id": "x"}, timeout=15)
        assert r.status_code in (401, 403)
