package com.ruoyi.system.mapper.flash;

import org.apache.ibatis.annotations.Select;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Locale;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class FlashDeliveryPricingMapperContractTest {

    @Test
    void globalPricingLockUsesDatabaseRowLock() throws Exception {
        Method method = FlashDeliveryPricingMapper.class.getMethod("lockPricing");
        String sql = sql(method);

        assertTrue(sql.contains("flash_delivery_pricing_lock"));
        assertTrue(sql.contains("for update"));
    }

    @Test
    void currentPeriodUsesInclusiveStartExclusiveEndAndDoesNotHideDuplicates() throws Exception {
        Method method = FlashDeliveryPricingMapper.class.getMethod("selectAtTime", String.class);
        String sql = sql(method);

        assertTrue(sql.contains("start_time <= #{targettime}"));
        assertTrue(sql.contains("end_time > #{targettime}"));
        assertFalse(sql.contains("service_type"));
        assertFalse(sql.contains("limit"));
    }

    @Test
    void overlapQueryAllowsAdjacentPeriodsIncludingEndOfDay() throws Exception {
        Method method = FlashDeliveryPricingMapper.class.getMethod(
                "countOverlapping", String.class, String.class, Long.class);
        String sql = sql(method);

        assertTrue(sql.contains("start_time < #{endtime}"));
        assertTrue(sql.contains("end_time > #{starttime}"));
        assertFalse(sql.contains("service_type"));
    }

    private String sql(Method method) {
        return Arrays.stream(method.getAnnotation(Select.class).value())
                .reduce("", (left, right) -> left + " " + right)
                .replaceAll("\\s+", " ")
                .toLowerCase(Locale.ROOT);
    }
}
