import uuid
import pytest
from sqlalchemy import select
from app.db.session import SessionLocal
from app.models.audit import AuditLog
from app.models.inventory import BranchInventory, StockAdjustment
from test_products_inventory import headers, product, workspace
pytest_plugins=("test_workspace",)

def test_opening_stock_is_atomic_one_time_and_in_history(client,verified_user):
 data=workspace(client,verified_user,"Opening");business,branch=data['business']['id'],data['accessible_branches'][0]['id'];created=product(client,verified_user,business,"Initial").json();url=f"/api/businesses/{business}/products/{created['id']}/opening-stock"
 result=client.post(url,json={'branch_id':branch,'quantity':'12','comment':'Initial count'},headers=headers(verified_user));assert result.status_code==201 and result.json()['resulting_quantity']==12
 assert client.post(url,json={'branch_id':branch,'quantity':'1'},headers=headers(verified_user)).status_code==422
 db=SessionLocal()
 try:
  movement=db.scalar(select(StockAdjustment).where(StockAdjustment.product_id==uuid.UUID(created['id'])));assert movement.reason=='OPENING_STOCK' and movement.quantity_changed==12
  assert db.scalar(select(BranchInventory.quantity).where(BranchInventory.product_id==uuid.UUID(created['id'])))==12
  assert db.scalar(select(AuditLog).where(AuditLog.action=='OPENING_STOCK_RECORDED',AuditLog.entity_id==uuid.UUID(created['id']))).branch_id==uuid.UUID(branch)
 finally:db.close()
 assert client.get(f"/api/businesses/{business}/products/history?reason=OPENING_STOCK",headers=headers(verified_user)).json()[0]['product_id']==created['id']
 assert client.get(f"/api/businesses/{business}/products/{created['id']}/stock-history",headers=headers(verified_user)).status_code==200

def test_opening_stock_rejects_invalid_quantity_and_late_activity(client,verified_user):
 data=workspace(client,verified_user,"Opening safe");business,branch=data['business']['id'],data['accessible_branches'][0]['id'];created=product(client,verified_user,business,"Late").json();url=f"/api/businesses/{business}/products/{created['id']}/opening-stock"
 assert client.post(url,json={'branch_id':branch,'quantity':'0'},headers=headers(verified_user)).status_code==422
 assert client.post(f"/api/businesses/{business}/branches/{branch}/stock-adjustments",json={'product_id':created['id'],'quantity_changed':'2','reason':'RESTOCK'},headers=headers(verified_user)).status_code==201
 assert client.post(url,json={'branch_id':branch,'quantity':'3'},headers=headers(verified_user)).status_code==422
