"""已登录的接口测试客户端：自动带会话 Cookie 与 CSRF 头。"""
import pytest
from fastapi.testclient import TestClient

from flyway.api.deps import CSRF_HEADER, get_db
from flyway.api.main import create_app
from flyway.auth.service import create_user


def _client(factory, username, password, admin):
    with factory() as s, s.begin():
        create_user(s, username, password, admin=admin, first_name=username.title())
    app = create_app()

    def override():
        with factory() as s:
            yield s

    app.dependency_overrides[get_db] = override
    client = TestClient(app, base_url="https://testserver")
    r = client.post("/api/auth/login", json={"username": username, "password": password})
    assert r.status_code == 200, r.text
    client.headers[CSRF_HEADER] = r.json()["csrf_token"]
    return client


@pytest.fixture
def admin_api(factory):
    with _client(factory, "boss", "boss-secret", True) as c:
        yield c


@pytest.fixture
def staff_api(factory):
    with _client(factory, "sam", "sam-secret", False) as c:
        yield c

NZ_15 = "2026-03-02T15:00:00+13:00"


def make_client_product(api, name="Acme", title="Kiwi", default_unit=1, available_unit=None):
    c = api.post("/api/clients", json={"name": name}).json()
    p = api.post("/api/products", json={"title": title, "default_unit": default_unit,
                                        "available_unit": available_unit}).json()
    return c["id"], p["id"]


def make_load_in(api, client_id, product_id, qty, code="LI-1", complete=True, batch="B1", unit=1):
    r = api.post("/api/load-ins", json={"client_id": client_id, "code": code, "date": NZ_15, "from_location": "Farm",
                                        "from_rmp": "R1", "lines": [{"product_id": product_id,
                                                                     "batch_number": batch, "quantity": qty, "unit": unit}]})
    assert r.status_code == 200, r.text
    if complete:
        r = api.post(f"/api/load-ins/{r.json()['id']}/complete")
        assert r.status_code == 200, r.text
    return r.json()
