from sqlalchemy.orm import Session
from app.models.branch import Branch
from .registry import register
import uuid

SEED_BRANCHES = [
    {
        "code": "HQ",
        "name": "Head Office",
        "location": "Gaborone",
        "is_head_office": True,
        "active": True,
        "phone": "+267 1234567",
        "email": "hq@company.com",
        "address": "Plot 1234, Main Mall, Gaborone",
        "timezone": "Africa/Gaborone",
        "currency": "BWP",
    },
    {
        "code": "MAIN",
        "name": "Main Branch",
        "location": "Gaborone",
        "is_head_office": False,
        "active": True,
        "phone": "+267 2345678",
        "email": "main@company.com",
        "address": "Plot 5678, CBD, Gaborone",
        "timezone": "Africa/Gaborone",
        "currency": "BWP",
    },
]

@register("branches")
def seed_branches(db: Session):
    """Seed default branches"""
    existing = {b.code: b for b in db.query(Branch).all()}

    for branch_data in SEED_BRANCHES:
        code = branch_data["code"]
        if code in existing:
            # Update existing branch
            branch = existing[code]
            for key, value in branch_data.items():
                if key != "code":  # Don't update code
                    setattr(branch, key, value)
            db.add(branch)
            print(f"[SEED] Updated branch: {code}")
        else:
            # Create new branch
            branch = Branch(
                id=str(uuid.uuid4()),
                **branch_data
            )
            db.add(branch)
            db.flush()
            existing[code] = branch
            print(f"[SEED] Created branch: {code}")

    db.commit()
    print(f"[SEED] Branches seeded successfully: {len(SEED_BRANCHES)} total")
