from marshmallow import Schema, fields, validate


class _StoreMini(Schema):
    id = fields.Integer()
    code = fields.String()
    name = fields.String()


class WarehouseLocationSchema(Schema):
    id = fields.Integer(dump_only=True)
    warehouse_id = fields.Integer(dump_only=True)
    code = fields.String(required=True, validate=validate.Length(min=1, max=40))
    name = fields.String(allow_none=True, validate=validate.Length(max=120))
    is_active = fields.Boolean(load_default=True)
    notes = fields.String(allow_none=True)
    created_at = fields.DateTime(dump_only=True)


class WarehouseSchema(Schema):
    id = fields.Integer(dump_only=True)
    store_id = fields.Integer(required=True)
    store = fields.Nested(_StoreMini, dump_only=True)
    code = fields.String(required=True, validate=validate.Length(min=1, max=30))
    name = fields.String(required=True, validate=validate.Length(min=1, max=120))
    is_default = fields.Boolean(load_default=False)
    is_active = fields.Boolean(load_default=True)
    notes = fields.String(allow_none=True)
    locations = fields.Nested(WarehouseLocationSchema, many=True, dump_only=True)
    locations_count = fields.Method("_loc_count", dump_only=True)
    items_count = fields.Method("_items_count", dump_only=True)
    created_at = fields.DateTime(dump_only=True)

    def _loc_count(self, o):
        return len(o.locations) if o.locations else 0

    def _items_count(self, o):
        # cuenta product_items en este warehouse (lazy: usar count() para no traer todo)
        from ..models import ProductItem
        return ProductItem.query.filter_by(warehouse_id=o.id).count()


class MoveItemSchema(Schema):
    """Mover una unidad a otro almacén / location (puede ser otra sede)."""
    warehouse_id = fields.Integer(required=True)
    location_id = fields.Integer(allow_none=True, load_default=None)
    notes = fields.String(allow_none=True, validate=validate.Length(max=500))
