from sqlalchemy.orm import Session

from app.models.sales import Customer
from app.constants.walkin_customer import WALKIN_CUSTOMER_ID
from .registry import register


@register("walkin_customer")
def seed_walkin_customer(db: Session):
    """
    Seed the system Walk-in Customer.

    This is the only customer seeded on a fresh ERP installation.
    All sales and invoices issued without a named customer are automatically
    assigned to this record, making it possible to track and report on
    anonymous walk-in traffic as an aggregate.
    """
    existing = db.query(Customer).filter(Customer.id == WALKIN_CUSTOMER_ID).first()
    if existing:
        # Ensure system fields are still correct even if someone accidentally edited the record
        changed = False
        if existing.name != "Walk-in Customer":
            existing.name = "Walk-in Customer"
            changed = True
        if existing.customer_type != "walk_in":
            existing.customer_type = "walk_in"
            changed = True
        if not existing.active:
            existing.active = True
            changed = True
        if changed:
            db.add(existing)
            db.commit()
        return

    customer = Customer(
        id=WALKIN_CUSTOMER_ID,
        name="Walk-in Customer",
        email=None,
        phone=None,
        address=None,
        customer_type="walk_in",
        payment_terms=0,
        credit_limit=0,
        active=True,
        notes=(
            "System-generated Walk-in Customer. "
            "All sales and invoices without a named customer are tracked here."
        ),
    )
    db.add(customer)
    db.commit()
    print(f"[seed] Walk-in Customer created (id={WALKIN_CUSTOMER_ID})")
