package com.snack.server.module.order.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.snack.server.module.order.entity.Order;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;

/**
 * 订单主表 Mapper
 */
@Mapper
public interface OrderMapper extends BaseMapper<Order> {

    /**
     * 更新订单状态（条件更新，防止状态错乱）
     * @return 受影响行数；0 表示状态已被其他流程修改
     */
    @Update("UPDATE orders SET status = #{toStatus}, " +
            "  pay_time = IF(#{toStatus} = 1, NOW(), pay_time), " +
            "  deliver_time = IF(#{toStatus} = 2, NOW(), deliver_time), " +
            "  receive_time = IF(#{toStatus} = 3, NOW(), receive_time), " +
            "  cancel_time = IF(#{toStatus} = 4, NOW(), cancel_time), " +
            "  finish_time = IF(#{toStatus} = 3, NOW(), finish_time) " +
            "WHERE id = #{id} AND status = #{fromStatus}")
    int updateStatusIfMatch(@Param("id") Long id,
                            @Param("fromStatus") Integer fromStatus,
                            @Param("toStatus") Integer toStatus);

    /**
     * 填写物流信息
     */
    @Update("UPDATE orders SET tracking_company = #{company}, tracking_no = #{trackingNo}, " +
            "  status = 2, deliver_time = NOW() " +
            "WHERE id = #{id} AND status = 1")
    int deliverOrder(@Param("id") Long id,
                     @Param("company") String company,
                     @Param("trackingNo") String trackingNo);

    /**
     * 支付成功回调：写入支付信息 + 状态切到待发货
     * 仅在 status = 0 (待付款) 时生效
     */
    @Update("UPDATE orders SET status = 1, pay_channel = #{payChannel}, pay_trade_no = #{payTradeNo}, " +
            "  pay_time = NOW() " +
            "WHERE id = #{id} AND status = 0")
    int markAsPaid(@Param("id") Long id,
                   @Param("payChannel") String payChannel,
                   @Param("payTradeNo") String payTradeNo);

    /**
     * 退款成功回调：写入退款信息 + 状态切到已退款
     * 仅在 status IN (1, 2, 3) 时生效
     */
    @Update("UPDATE orders SET status = 5, refund_trade_no = #{refundTradeNo}, " +
            "  refund_time = NOW(), refund_reason = #{reason} " +
            "WHERE id = #{id} AND status IN (1, 2, 3)")
    int markAsRefunded(@Param("id") Long id,
                       @Param("refundTradeNo") String refundTradeNo,
                       @Param("reason") String reason);
}
