from marshmallow import Schema, fields, validate

from .customer import CustomerSchema


class _SaleRef(Schema):
    id = fields.Integer()
    number = 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 _ItemRef(Schema):
    id = fields.Integer()
    serial = fields.String()
    barcode = fields.String()
    status = fields.Method("_status")
    product = fields.Method("_product")

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

    def _product(self, o):
        return {"id": o.product.id, "name": o.product.name} if o.product else None


class ReturnItemSchema(Schema):
    id = fields.Integer(dump_only=True)
    product_item_id = fields.Integer(required=True)
    type = fields.String(required=True, validate=validate.OneOf(
        ["refund_available", "refund_damaged", "warranty", "loss"]
    ))
    notes = fields.String(allow_none=True)
    product_item = fields.Nested(_ItemRef, dump_only=True)


class ReturnSchema(Schema):
    id = fields.Integer(dump_only=True)
    number = fields.String(dump_only=True)
    sale_id = fields.Integer(allow_none=True)
    sale = fields.Nested(_SaleRef, dump_only=True)
    customer_id = fields.Integer(allow_none=True)
    customer = fields.Nested(CustomerSchema, dump_only=True)
    status = fields.Method("_status", dump_only=True)
    reason = fields.String(allow_none=True, validate=validate.Length(max=120))
    notes = fields.String(allow_none=True)
    items = fields.Nested(ReturnItemSchema, many=True, dump_only=True)
    user_id = fields.Integer(dump_only=True, allow_none=True)
    user = fields.Nested(_UserRef, dump_only=True, allow_none=True)
    processed_at = fields.DateTime(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


class CreateReturnSchema(Schema):
    sale_id = fields.Integer(allow_none=True)
    customer_id = fields.Integer(allow_none=True)
    reason = fields.String(allow_none=True, validate=validate.Length(max=120))
    notes = fields.String(allow_none=True)
    items = fields.List(fields.Nested(ReturnItemSchema), required=True, validate=validate.Length(min=1))
