from marshmallow import Schema, fields, validate

from .supplier import SupplierSchema


class _ProductRef(Schema):
    id = fields.Integer()
    name = fields.String()
    slug = fields.String()
    sku = fields.String()
    image_url = fields.String()


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


class _UserRef(Schema):
    id = fields.Integer()
    full_name = fields.String()
    email = fields.String()
    role = fields.Method("_role")

    def _role(self, o):
        return o.role.value if hasattr(o.role, "value") else o.role


class _PayableRef(Schema):
    id = fields.Integer()
    total = fields.Decimal(as_string=True, places=2)
    paid = fields.Decimal(as_string=True, places=2)
    balance = fields.Decimal(as_string=True, places=2)
    due_date = fields.Date(allow_none=True)
    status = fields.Method("_status")
    is_overdue = fields.Boolean()

    def _status(self, o):
        return o.status.value if hasattr(o.status, "value") else o.status


class PurchaseItemSchema(Schema):
    id = fields.Integer(dump_only=True)
    product_id = fields.Integer(required=True)
    quantity = fields.Integer(required=True, validate=validate.Range(min=1, max=500))
    unit_cost = fields.Decimal(required=True, as_string=True, places=2)
    line_total = fields.Decimal(as_string=True, places=2, dump_only=True)
    product = fields.Nested(_ProductRef, dump_only=True)


class PurchaseSchema(Schema):
    id = fields.Integer(dump_only=True)
    number = fields.String(dump_only=True)
    supplier_id = fields.Integer(required=True)
    supplier = fields.Nested(SupplierSchema, dump_only=True)
    store_id = fields.Integer(allow_none=True)
    store = fields.Nested(_StoreRef, dump_only=True, allow_none=True)
    status = fields.Method("_status", dump_only=True)
    subtotal = fields.Decimal(as_string=True, places=2, dump_only=True)
    discount = fields.Decimal(as_string=True, places=2, dump_only=True)
    total = fields.Decimal(as_string=True, places=2, dump_only=True)
    currency = fields.String()
    notes = fields.String(allow_none=True)
    received_at = fields.DateTime(dump_only=True, allow_none=True)
    items = fields.Nested(PurchaseItemSchema, many=True, dump_only=True)
    items_count = fields.Method("_items_count", dump_only=True)
    units_total = fields.Method("_units_total", dump_only=True)
    payable = fields.Nested(_PayableRef, dump_only=True, allow_none=True)
    user_id = fields.Integer(dump_only=True, allow_none=True)
    user = fields.Nested(_UserRef, dump_only=True, allow_none=True)
    created_at = fields.DateTime(dump_only=True)

    def _status(self, o):
        return o.status.value if hasattr(o.status, "value") else o.status

    def _items_count(self, o):
        return len(o.items) if o.items else 0

    def _units_total(self, o):
        return sum(i.quantity for i in o.items) if o.items else 0


class CreatePurchaseSchema(Schema):
    supplier_id = fields.Integer(required=True)
    store_id = fields.Integer(allow_none=True, load_default=None)
    currency = fields.String(load_default="USD")
    notes = fields.String(allow_none=True)
    items = fields.List(
        fields.Nested(PurchaseItemSchema),
        required=True,
        validate=validate.Length(min=1, max=200),
    )


class ReceiveLineSchema(Schema):
    purchase_item_id = fields.Integer(required=True)
    serials = fields.List(fields.String(validate=validate.Length(min=1, max=120)), required=True)
    imeis = fields.List(fields.String(validate=validate.Length(max=40), allow_none=True), load_default=None)
    # Opcional: paralelo a serials. Si un slot viene vacío/None se autogenera.
    barcodes = fields.List(fields.String(validate=validate.Length(max=60), allow_none=True), load_default=None)
    warehouse_id = fields.Integer(allow_none=True, load_default=None)
    location_id = fields.Integer(allow_none=True, load_default=None)
    location = fields.String(allow_none=True, validate=validate.Length(max=80))


class ReceivePurchaseSchema(Schema):
    items = fields.List(fields.Nested(ReceiveLineSchema), required=True, validate=validate.Length(min=1))
    due_date = fields.Date(allow_none=True)
    # Almacén destino por defecto si las líneas no especifican uno individual
    default_warehouse_id = fields.Integer(allow_none=True, load_default=None)
