package de.votian.services.controller;

import de.votian.services.dto.PublicHolidayDayDto;
import de.votian.services.dto.PublicHolidayYearDto;
import de.votian.services.dto.UserSessionDto;
import de.votian.services.security.AccessControlService;
import de.votian.services.service.PublicHolidayService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;

import java.util.List;
import java.util.Objects;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

class PublicHolidayControllerTest {

    private PublicHolidayService publicHolidayService;
    private AccessControlService accessControlService;
    private PublicHolidayController controller;
    private Authentication authentication;
    private UserSessionDto user;

    @BeforeEach
    void setUp() {
        publicHolidayService = mock(PublicHolidayService.class);
        accessControlService = mock(AccessControlService.class);
        controller = new PublicHolidayController(publicHolidayService, accessControlService);
        authentication = mock(Authentication.class);
        user = new UserSessionDto();
        user.setUserType(1);
        user.setHeadquartersId(1L);
        user.setEmployeeId(23L);

        when(accessControlService.sessionUser(authentication)).thenReturn(user);
        when(accessControlService.canManageHeadquarters(user)).thenReturn(true);
        when(accessControlService.canAccessHeadquarters(user, 1L)).thenReturn(true);
    }

    @Test
    void getYearRejectsUnauthorizedUsers() {
        when(accessControlService.canManageHeadquarters(user)).thenReturn(false);

        ResponseEntity<PublicHolidayYearDto> response = controller.getYear(1L, 2026, authentication);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
    }

    @Test
    void saveYearDelegatesToService() {
        PublicHolidayController.PublicHolidayUpdateRequest request = new PublicHolidayController.PublicHolidayUpdateRequest();
        PublicHolidayDayDto day = new PublicHolidayDayDto();
        day.setMonth(12);
        day.setDay(25);
        day.setHoliday(true);
        request.days = List.of(day);

        PublicHolidayYearDto dto = new PublicHolidayYearDto();
        dto.setYear(2026);

        when(publicHolidayService.saveYear(1L, 2026, request.days)).thenReturn(dto);

        ResponseEntity<PublicHolidayYearDto> response = controller.saveYear(1L, 2026, request, authentication);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody()).isNotNull();
        assertThat(Objects.requireNonNull(response.getBody()).getYear()).isEqualTo(2026);
        verify(publicHolidayService).saveYear(1L, 2026, request.days);
    }
}
