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.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/api/public-holidays")
public class PublicHolidayController {

    private final PublicHolidayService publicHolidayService;
    private final AccessControlService accessControlService;

    public PublicHolidayController(PublicHolidayService publicHolidayService,
                                   AccessControlService accessControlService) {
        this.publicHolidayService = publicHolidayService;
        this.accessControlService = accessControlService;
    }

    @GetMapping
    public ResponseEntity<PublicHolidayYearDto> getYear(@RequestParam Long hqId,
                                                        @RequestParam int year,
                                                        Authentication authentication) {
        UserSessionDto user = accessControlService.sessionUser(authentication);
        if (!accessControlService.canManageHeadquarters(user) || !accessControlService.canAccessHeadquarters(user, hqId)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        return ResponseEntity.ok(publicHolidayService.getYear(hqId, year));
    }

    @PutMapping
    public ResponseEntity<PublicHolidayYearDto> saveYear(@RequestParam Long hqId,
                                                         @RequestParam int year,
                                                         @RequestBody PublicHolidayUpdateRequest request,
                                                         Authentication authentication) {
        UserSessionDto user = accessControlService.sessionUser(authentication);
        if (!accessControlService.canManageHeadquarters(user) || !accessControlService.canAccessHeadquarters(user, hqId)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        return ResponseEntity.ok(publicHolidayService.saveYear(hqId, year, request.days));
    }

    public static class PublicHolidayUpdateRequest {
        public List<PublicHolidayDayDto> days = new ArrayList<>();
    }
}
