package com.ycwl.basic.face.pipeline.stages;

import com.ycwl.basic.face.pipeline.core.FaceMatchingContext;
import com.ycwl.basic.pipeline.core.StageResult;
import com.ycwl.basic.model.pc.face.entity.FaceEntity;
import com.ycwl.basic.model.pc.source.entity.MemberSourceEntity;
import com.ycwl.basic.service.pc.processor.SourceRelationProcessor;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

/**
 * ProcessFreeSourceStage 单元测试
 */
@ExtendWith(MockitoExtension.class)
class ProcessFreeSourceStageTest {

    @Mock
    private SourceRelationProcessor sourceRelationProcessor;

    @InjectMocks
    private ProcessFreeSourceStage stage;

    private FaceMatchingContext context;
    private FaceEntity face;

    @BeforeEach
    void setUp() {
        context = FaceMatchingContext.forAutoMatching(1L, true);

        face = new FaceEntity();
        face.setId(1L);
        face.setMemberId(100L);
        face.setScenicId(10L);

        context.setFace(face);
    }

    @Test
    void testExecute_MemberSourceListNull_Skipped() {
        // Given: memberSourceList为null
        context.setMemberSourceList(null);

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isSkipped());
        verify(sourceRelationProcessor, never())
                .processFreeSourceLogic(anyList(), anyLong(), anyBoolean());
    }

    @Test
    void testExecute_MemberSourceListEmpty_Skipped() {
        // Given: memberSourceList为空
        context.setMemberSourceList(new ArrayList<>());

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isSkipped());
        verify(sourceRelationProcessor, never())
                .processFreeSourceLogic(anyList(), anyLong(), anyBoolean());
    }

    @Test
    void testExecute_Success_WithFreeSource() {
        // Given: 有免费源文件
        List<MemberSourceEntity> memberSourceList = createMemberSourceList(5);
        context.setMemberSourceList(memberSourceList);

        List<Long> freeSourceIds = Arrays.asList(1L, 2L, 3L);
        when(sourceRelationProcessor.processFreeSourceLogic(memberSourceList, 10L, true))
                .thenReturn(freeSourceIds);

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isSuccess());
        assertTrue(result.getMessage().contains("确定了3个免费源文件"));
        assertEquals(freeSourceIds, context.getFreeSourceIds());
        verify(sourceRelationProcessor, times(1))
                .processFreeSourceLogic(memberSourceList, 10L, true);
    }

    @Test
    void testExecute_Success_NoFreeSource() {
        // Given: 没有免费源文件
        List<MemberSourceEntity> memberSourceList = createMemberSourceList(5);
        context.setMemberSourceList(memberSourceList);

        List<Long> freeSourceIds = new ArrayList<>();
        when(sourceRelationProcessor.processFreeSourceLogic(memberSourceList, 10L, true))
                .thenReturn(freeSourceIds);

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isSuccess());
        assertTrue(result.getMessage().contains("确定了0个免费源文件"));
        assertEquals(freeSourceIds, context.getFreeSourceIds());
    }

    @Test
    void testExecute_Success_NullFreeSource() {
        // Given: 返回null(无免费源文件)
        List<MemberSourceEntity> memberSourceList = createMemberSourceList(5);
        context.setMemberSourceList(memberSourceList);

        when(sourceRelationProcessor.processFreeSourceLogic(memberSourceList, 10L, true))
                .thenReturn(null);

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isSuccess());
        assertTrue(result.getMessage().contains("确定了0个免费源文件"));
        assertNull(context.getFreeSourceIds());
    }

    @Test
    void testExecute_OldUser() {
        // Given: 老用户
        context = FaceMatchingContext.forAutoMatching(1L, false);
        context.setFace(face);

        List<MemberSourceEntity> memberSourceList = createMemberSourceList(3);
        context.setMemberSourceList(memberSourceList);

        List<Long> freeSourceIds = Arrays.asList(1L);
        when(sourceRelationProcessor.processFreeSourceLogic(memberSourceList, 10L, false))
                .thenReturn(freeSourceIds);

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isSuccess());
        verify(sourceRelationProcessor, times(1))
                .processFreeSourceLogic(memberSourceList, 10L, false);
    }

    @Test
    void testExecute_ProcessorFailed_Degraded() {
        // Given: 处理器执行失败
        List<MemberSourceEntity> memberSourceList = createMemberSourceList(3);
        context.setMemberSourceList(memberSourceList);

        when(sourceRelationProcessor.processFreeSourceLogic(memberSourceList, 10L, true))
                .thenThrow(new RuntimeException("Processor error"));

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isDegraded());
        assertTrue(result.getMessage().contains("免费源文件处理失败"));
        verify(sourceRelationProcessor, times(1))
                .processFreeSourceLogic(memberSourceList, 10L, true);
    }

    @Test
    void testExecute_DifferentScenicId() {
        // Given: 不同的景区ID
        face.setScenicId(888L);

        List<MemberSourceEntity> memberSourceList = createMemberSourceList(3);
        context.setMemberSourceList(memberSourceList);

        List<Long> freeSourceIds = Arrays.asList(1L, 2L);
        when(sourceRelationProcessor.processFreeSourceLogic(memberSourceList, 888L, true))
                .thenReturn(freeSourceIds);

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isSuccess());
        verify(sourceRelationProcessor, times(1))
                .processFreeSourceLogic(memberSourceList, 888L, true);
    }

    @Test
    void testExecute_AllSourcesFree() {
        // Given: 所有源文件都免费
        List<MemberSourceEntity> memberSourceList = createMemberSourceList(5);
        context.setMemberSourceList(memberSourceList);

        List<Long> freeSourceIds = Arrays.asList(1L, 2L, 3L, 4L, 5L);
        when(sourceRelationProcessor.processFreeSourceLogic(memberSourceList, 10L, true))
                .thenReturn(freeSourceIds);

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isSuccess());
        assertTrue(result.getMessage().contains("确定了5个免费源文件"));
        assertEquals(5, context.getFreeSourceIds().size());
    }

    @Test
    void testExecute_NullPointerException_Degraded() {
        // Given: 空指针异常
        List<MemberSourceEntity> memberSourceList = createMemberSourceList(3);
        context.setMemberSourceList(memberSourceList);

        when(sourceRelationProcessor.processFreeSourceLogic(memberSourceList, 10L, true))
                .thenThrow(new NullPointerException("Null processor"));

        // When
        StageResult<FaceMatchingContext> result = stage.execute(context);

        // Then
        assertTrue(result.isDegraded());
        assertTrue(result.getMessage().contains("免费源文件处理失败"));
    }

    private List<MemberSourceEntity> createMemberSourceList(int count) {
        List<MemberSourceEntity> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            MemberSourceEntity entity = new MemberSourceEntity();
            entity.setMemberId(100L);
            entity.setSourceId((long) (i + 1));
            list.add(entity);
        }
        return list;
    }
}
