from marshmallow import Schema, fields, validate, validates_schema, ValidationError

from .customer import CustomerSchema


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


class _ItemRef(Schema):
    id = fields.Integer()
    serial = fields.String()
    barcode = fields.String()


class _UserRef(Schema):
    id = fields.Integer()
    full_name = fields.String()
    email = fields.String()


class SaleItemSchema(Schema):
    id = fields.Integer(dump_only=True)
    product_id = fields.Integer(required=True)
    product_item_id = fields.Integer(dump_only=True)
    unit_price = fields.Decimal(as_string=True, places=2)
    quantity = fields.Integer()
    line_total = fields.Decimal(as_string=True, places=2)
    product = fields.Nested(_ProductRef, dump_only=True)
    product_item = fields.Nested(_ItemRef, dump_only=True)


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


class _PaymentMethodRef(Schema):
    id = fields.Integer()
    name = fields.String()
    code = fields.String()
    adjustment_percent = fields.Decimal(as_string=True, places=2)
    instructions = fields.String()
    requires_proof = fields.Boolean()
    currency_id = fields.Integer(allow_none=True)
    currency = fields.Nested(_CurrencyMini, allow_none=True)


class SaleAttachmentSchema(Schema):
    id = fields.Integer(dump_only=True)
    sale_id = fields.Integer(dump_only=True)
    kind = fields.Method("_get_kind", dump_only=True)
    file_url = fields.String(dump_only=True)
    filename = fields.String(dump_only=True)
    mime_type = fields.String(dump_only=True)
    note = fields.String(dump_only=True, allow_none=True)
    uploaded_by = fields.Nested(_UserRef, dump_only=True, allow_none=True)
    created_at = fields.DateTime(dump_only=True)

    def _get_kind(self, o):
        return o.kind.value if hasattr(o.kind, "value") else o.kind


class SaleSchema(Schema):
    id = fields.Integer(dump_only=True)
    number = fields.String(dump_only=True)
    channel = fields.Method("_get_channel", dump_only=True)
    status = fields.Method("_get_status", dump_only=True)
    payment_status = fields.Method("_get_payment_status", dump_only=True)
    fulfillment_status = fields.Method("_get_fulfillment_status", dump_only=True)
    customer_id = fields.Integer(dump_only=True)
    customer = fields.Nested(CustomerSchema, dump_only=True)
    user_id = fields.Integer(dump_only=True)
    user = fields.Nested(_UserRef, dump_only=True)
    payment_method_id = fields.Integer(dump_only=True, allow_none=True)
    payment_method = fields.Nested(_PaymentMethodRef, dump_only=True, allow_none=True)
    subtotal = fields.Decimal(as_string=True, places=2, dump_only=True)
    discount = fields.Decimal(as_string=True, places=2, dump_only=True)
    surcharge = fields.Decimal(as_string=True, places=2, dump_only=True)
    total = fields.Decimal(as_string=True, places=2, dump_only=True)
    currency = fields.String(dump_only=True)
    payment_currency = fields.String(dump_only=True, allow_none=True)
    payment_exchange_rate = fields.Decimal(as_string=True, places=6, dump_only=True, allow_none=True)
    payment_total = fields.Decimal(as_string=True, places=2, dump_only=True, allow_none=True)
    notes = fields.String(allow_none=True)
    items = fields.Nested(SaleItemSchema, many=True, dump_only=True)
    attachments = fields.Nested(SaleAttachmentSchema, many=True, dump_only=True)
    trade_ins = fields.Method("_get_trade_ins", dump_only=True)
    payments = fields.Method("_get_payments", dump_only=True)
    created_at = fields.DateTime(dump_only=True)

    def _get_trade_ins(self, o):
        items = getattr(o, "trade_ins", []) or []
        return [{
            "id": t.id,
            "model_name": t.model_name,
            "color": t.color,
            "battery_pct": t.battery_pct,
            "imei": t.imei,
            "serial": t.serial,
            "valuation_amount": str(t.valuation_amount),
            "currency": t.currency,
            "notes": t.notes,
            "user": {"id": t.user.id, "full_name": t.user.full_name} if t.user else None,
            "created_at": t.created_at.isoformat() if t.created_at else None,
        } for t in items]

    def _get_payments(self, o):
        ar = getattr(o, "receivable", None)
        if not ar or not ar.payments:
            return []
        return [{
            "id": p.id,
            "amount": str(p.amount),
            "currency": p.currency,
            "method": p.payment_method.name if getattr(p, "payment_method", None) else (p.method or "—"),
            "method_id": p.payment_method_id,
            "reference": p.reference,
            "paid_at": p.paid_at.isoformat() if p.paid_at else None,
            "user": {"id": p.user.id, "full_name": p.user.full_name} if p.user else None,
        } for p in (ar.payments or [])]
    updated_at = fields.DateTime(dump_only=True)

    def _get_channel(self, o):
        return o.channel.value if hasattr(o.channel, "value") else o.channel

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

    def _get_payment_status(self, o):
        return o.payment_status.value if hasattr(o.payment_status, "value") else o.payment_status

    def _get_fulfillment_status(self, o):
        return o.fulfillment_status.value if hasattr(o.fulfillment_status, "value") else o.fulfillment_status


class UpdateFulfillmentSchema(Schema):
    fulfillment_status = fields.String(
        required=True,
        validate=validate.OneOf(["pending", "in_progress", "completed"]),
    )
    note = fields.String(allow_none=True, validate=validate.Length(max=500))


class OrderLineInputSchema(Schema):
    product_id = fields.Integer(required=True)
    quantity = fields.Integer(required=True, validate=validate.Range(min=1, max=20))


class CreateOrderSchema(Schema):
    items = fields.List(
        fields.Nested(OrderLineInputSchema), required=True, validate=validate.Length(min=1, max=50)
    )
    customer = fields.Nested(CustomerSchema, required=True)
    payment_method_id = fields.Integer(allow_none=True)
    notes = fields.String(allow_none=True)


class POSLineSchema(Schema):
    product_item_id = fields.Integer(allow_none=True)
    product_id = fields.Integer(allow_none=True)
    quantity = fields.Integer(load_default=1, validate=validate.Range(min=1, max=20))

    @validates_schema
    def validate_one(self, data, **kwargs):
        if not data.get("product_item_id") and not data.get("product_id"):
            raise ValidationError("Indica product_item_id (unidad escaneada) o product_id (con cantidad)")


class POSPaymentSchema(Schema):
    """Un pago individual en una venta POS (split payment)."""
    payment_method_id = fields.Integer(required=True)
    amount = fields.Decimal(required=True, as_string=True, places=2,
                            validate=validate.Range(min=0, min_inclusive=False))
    reference = fields.String(allow_none=True, validate=validate.Length(max=120))
    notes = fields.String(allow_none=True)


class POSTradeInSchema(Schema):
    """iPhone usado recibido en parte de pago."""
    model_name = fields.String(required=True, validate=validate.Length(min=1, max=120))
    color = fields.String(allow_none=True, validate=validate.Length(max=40))
    battery_pct = fields.Integer(allow_none=True, validate=validate.Range(min=0, max=100))
    imei = fields.String(allow_none=True, validate=validate.Length(max=40))
    serial = fields.String(allow_none=True, validate=validate.Length(max=120))
    valuation_amount = fields.Decimal(required=True, as_string=True, places=2,
                                      validate=validate.Range(min=0, min_inclusive=False))
    notes = fields.String(allow_none=True)


class CasheaPlanSchema(Schema):
    """Plan de cuotas Cashea: inicial = sum(payments) + N cuotas cada 15 días."""
    installments = fields.Integer(required=True, validate=validate.Range(min=2, max=6))


class CreatePOSSaleSchema(Schema):
    customer_id = fields.Integer(required=True)
    items = fields.List(fields.Nested(POSLineSchema), required=True, validate=validate.Length(min=1, max=100))
    # NUEVO: array de pagos. La suma de payments + trade_ins debe ser exactamente
    # igual al total de la venta. El backend rechaza si no cuadra (salvo Cashea).
    payments = fields.List(fields.Nested(POSPaymentSchema), required=True,
                           validate=validate.Length(min=1, max=10))
    trade_ins = fields.List(fields.Nested(POSTradeInSchema), load_default=list,
                            validate=validate.Length(max=5))
    discount = fields.Decimal(as_string=True, places=2, load_default="0")
    notes = fields.String(allow_none=True)
    # Si viene, la venta queda con plan Cashea (cuotas a crédito): la
    # inicial es lo cubierto por payments, el resto se divide en N cuotas
    # vencidas cada 15 días.
    cashea_plan = fields.Nested(CasheaPlanSchema, allow_none=True, load_default=None)


class ConfirmWebSaleSchema(Schema):
    payment_method_id = fields.Integer(required=True)
    payment_now = fields.Boolean(load_default=True)
    due_date = fields.Date(allow_none=True)
    payment_reference = fields.String(allow_none=True, validate=validate.Length(max=120))
