from sqlalchemy import select, or_, func
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.customer import Customer
from app.models.wallet import Wallet
from app.core.exceptions import not_found, conflict

class CustomerService:
    @staticmethod
    async def create(db, brand_id, data):
        exists = await db.scalar(select(Customer).where(Customer.brand_id == brand_id, Customer.mobile == data.mobile))
        if exists: raise conflict("Customer mobile already exists")
        count = await db.scalar(select(func.count(Customer.id)).where(Customer.brand_id == brand_id))
        customer = Customer(brand_id=brand_id, customer_code=f"C{brand_id:03d}{int(count or 0)+1:06d}", **data.model_dump())
        db.add(customer)
        await db.flush()
        db.add(Wallet(brand_id=brand_id, customer_id=customer.id, balance=0))
        await db.commit()
        await db.refresh(customer)
        return customer

    @staticmethod
    async def get(db, brand_id, customer_id):
        obj = await db.scalar(select(Customer).where(Customer.id == customer_id, Customer.brand_id == brand_id))
        if not obj: raise not_found("Customer not found")
        return obj
