package com.starry.admin.modules.order.module.dto;

import com.starry.admin.modules.order.module.constant.OrderConstant.OrderActor;
import com.starry.admin.modules.order.module.constant.OrderConstant.OrderTriggerSource;
import java.util.Objects;
import lombok.Data;
import org.springframework.lang.Nullable;

/**
 * 订单完成上下文信息，用于记录触发来源与操作人。
 */
@Data
public class OrderCompletionContext {

    /** 操作人类型，系统任务使用 SYSTEM。 */
    private OrderActor operatorActor = OrderActor.SYSTEM;

    /** 操作人ID，SYSTEM 时允许为空。 */
    @Nullable
    private String operatorId;

    /** 触发来源描述，例如 wx_customer、scheduler、admin_panel。 */
    private OrderTriggerSource triggerSource = OrderTriggerSource.UNKNOWN;

    /** 额外备注信息，可为空。 */
    @Nullable
    private String comment;

    /** 是否强制发送完成通知。 */
    private boolean forceNotify;

    public static OrderCompletionContext of(OrderActor actor, @Nullable String operatorId, OrderTriggerSource triggerSource) {
        Objects.requireNonNull(actor, "operator actor cannot be null");
        Objects.requireNonNull(triggerSource, "triggerSource cannot be null");
        if (actor != OrderActor.SYSTEM && operatorId == null) {
            throw new IllegalArgumentException("operatorId is required for actor " + actor);
        }
        OrderCompletionContext context = new OrderCompletionContext();
        context.setOperatorActor(actor);
        context.setOperatorId(operatorId);
        context.setTriggerSource(triggerSource);
        return context;
    }

    public static OrderCompletionContext of(OrderActor actor, @Nullable String operatorId, OrderTriggerSource triggerSource, @Nullable String comment) {
        return of(actor, operatorId, triggerSource).withComment(comment);
    }

    public static OrderCompletionContext scheduler(@Nullable String comment) {
        return of(OrderActor.SYSTEM, null, OrderTriggerSource.SCHEDULER, comment);
    }

    public static OrderCompletionContext system(OrderTriggerSource triggerSource, @Nullable String comment) {
        return of(OrderActor.SYSTEM, null, triggerSource, comment);
    }

    public OrderCompletionContext withForceNotify(boolean forceNotify) {
        this.forceNotify = forceNotify;
        return this;
    }

    public OrderCompletionContext withComment(@Nullable String comment) {
        this.comment = comment;
        return this;
    }

    public OrderCompletionContext withTriggerSource(OrderTriggerSource triggerSource) {
        this.triggerSource = Objects.requireNonNull(triggerSource, "triggerSource");
        return this;
    }
}
