"""Shared helpers for DB-backed module tests (receive stock through the real API)."""
from sqlalchemy import text

from conftest import login, login_as

API = "/api/v1"


async def q(db, sql, **params):
    async with db.connect() as conn:
        return (await conn.execute(text(sql), params)).all()


async def one(db, sql, **params):
    return (await q(db, sql, **params))[0][0]


async def supplier(db, name="Farm Fresh Dairy Ltd"):
    return await one(db, "SELECT id FROM supplier WHERE name = :n", n=name)


async def product(db, sku):
    return await one(db, "SELECT id FROM product WHERE sku = :s", s=sku)


async def location(db, storage_type):
    return await one(
        db, "SELECT l.id FROM location l JOIN site s ON s.id = l.site_id "
            "WHERE s.type = 'DC' AND l.usage = 'INTERNAL' AND l.storage_type = :t", t=storage_type)


class Dc:
    """A DC staff session with small helpers for the receiving flow."""

    def __init__(self, client, db, headers):
        self.c, self.db, self.h = client, db, headers

    async def post(self, path, body=None, **kw):
        return await self.c.post(f"{API}{path}", json=body or {}, headers=self.h, **kw)

    async def receipt(self, supplier_id=None, **extra):
        r = await self.post("/receipts", {"supplier_id": supplier_id or await supplier(self.db),
                                          **extra})
        assert r.status_code == 201, r.text
        return r.json()["id"]

    async def line(self, rid, sku, qty, cartons=None):
        body = {"product_id": await product(self.db, sku), "qty": str(qty)}
        if cartons is not None:
            body["cartons"] = cartons
        r = await self.post(f"/receipts/{rid}/lines", body)
        assert r.status_code == 201, r.text
        return r.json()["id"]

    async def sample(self, line_id, day, **extra):
        return await self.post(f"/receipt-lines/{line_id}/date-samples",
                               {"printed_date": day, **extra})

    async def confirm(self, rid, entries, user_id=None):
        uid = user_id or await one(self.db, "SELECT id FROM app_user WHERE name='dc_staff'")
        return await self.post(f"/receipts/{rid}/confirm",
                               {"confirmed_by": uid, "storage_locations": entries})


async def receive_tomatoes(dc, db, weights, *, supplier_name="Savar Agro Growers"):
    """Receive one loose tomato line; each weight becomes its own crate and batch."""
    rid = await dc.receipt(supplier_id=await supplier(db, supplier_name))
    line = await dc.line(rid, "TOM", sum(float(w) for w in weights))
    r = await dc.confirm(rid, [{"line_id": line, "location_id": await location(db, "AMBIENT"),
                                "crates": [{"weight_kg": str(w)} for w in weights]}])
    assert r.status_code == 200, r.text
    return r.json()["batches"]


async def receive_milk(dc, db, qty=24, cartons=2, day="2026-09-30"):
    """Receive packaged milk with one sampled date: a single CAPTURED batch."""
    rid = await dc.receipt()
    line = await dc.line(rid, "MLK1L", qty, cartons=cartons)
    assert (await dc.sample(line, day)).status_code == 201
    r = await dc.confirm(rid, [{"line_id": line, "location_id": await location(db, "CHILLED")}])
    assert r.status_code == 200, r.text
    return r.json()["batches"][0]


def crate_code(batch):
    return f"C{batch['id']:06d}001"


async def advance(client, hours):
    h = await login(client, "head_office")
    r = await client.post(f"{API}/demo/clock", json={"hours": str(hours)}, headers=h)
    assert r.status_code == 200, r.text


async def stock_outlet(client, dc, db, outlet, *, tomatoes=(), milk_qty=None, to="OUT-DHN"):
    """Receive at the DC, ship everything to the outlet and scan it in (the real flow).

    Returns {"tomato": [batches], "milk": batch | None}; stock then sits in the outlet's stores.
    """
    tom = await receive_tomatoes(dc, db, list(tomatoes)) if tomatoes else []
    milk = await receive_milk(dc, db, qty=milk_qty) if milk_qty else None
    items = []
    if tom:
        items.append({"product_id": await product(db, "TOM"),
                      "qty": str(sum(float(b["qty"]) for b in tom))})
    if milk:
        items.append({"product_id": await product(db, "MLK1L"), "qty": str(milk_qty)})
    site = await one(db, "SELECT id FROM site WHERE code = :c", c=to)
    tr = (await client.post(f"{API}/transfers/dispatch", headers=dc.h,
                            json={"outlet_site_id": site, "items": items})).json()
    codes = [ln["crate_barcode"] for m in tr["moves"] for ln in m["lines"]]
    r = await client.post(f"{API}/transfers/{tr['id']}/load", headers=dc.h,
                          json={"scans": [{"code": c} for c in codes]})
    assert r.status_code == 200, r.text
    r = await client.post(f"{API}/transfers/{tr['id']}/depart", headers=dc.h,
                          json={"vehicle_type": "OPEN"})
    assert r.status_code == 200, r.text
    staff = outlet["staff"]
    r = await client.post(f"{API}/transfers/{tr['id']}/arrive", headers=staff,
                          json={"scans": [{"code": c} for c in codes]})
    assert r.status_code == 200 and r.json()["missing_crates"] == 0, r.text
    return {"tomato": tom, "milk": milk}


async def outlet_qty(db, batch_id, site_code="OUT-DHN"):
    """Total stock of a batch in the outlet's own stores."""
    return float(await one(
        db, "SELECT coalesce(sum(b.qty), 0) FROM inventory_balance b JOIN location l "
            "ON l.id = b.location_id JOIN site s ON s.id = l.site_id "
            "WHERE b.batch_id = :b AND s.code = :c AND l.usage = 'INTERNAL'",
        b=batch_id, c=site_code))


async def user_headers(client, db, role, site_id, *, email=None, password="123456",
                       name=None):
    """A real extra user (e.g. a manager at another outlet), logged in. Returns the headers."""
    from app.core.passwords import hash_password

    n = await one(db, "SELECT coalesce(max(id), 0) + 1 FROM app_user")
    email = email or f"user{n}@neuro.local"
    async with db.begin() as conn:
        await conn.execute(text(
            "INSERT INTO app_user (name, email, role, site_id, password_hash) "
            "VALUES (:n, :e, :r, :s, :h)"),
            {"n": name or f"user{n}", "e": email, "r": role, "s": site_id,
             "h": hash_password(password)})
    return await login_as(client, email, password)
