"""Assign branch_id on products missing it (use company HQ or first branch)."""
from app.core.database import SessionLocal
from app.models.inventory import Product
from app.models.branch import Branch

db = SessionLocal()
updated = 0
for product in db.query(Product).filter(Product.branch_id.is_(None)).all():
    branch = (
        db.query(Branch)
        .filter(Branch.is_head_office == True)
        .order_by(Branch.created_at.asc())
        .first()
    )
    if not branch:
        branch = db.query(Branch).order_by(Branch.created_at.asc()).first()
    if not branch:
        print("no branch found")
        break
    product.branch_id = branch.id
    updated += 1
    print(f"set branch {branch.code} on {product.name}")
db.commit()
print(f"updated={updated}")
db.close()
