package it.sw.pa.comune.artegna.web.rest;

import it.sw.pa.comune.artegna.repository.StrutturaRepository;
import it.sw.pa.comune.artegna.service.StrutturaQueryService;
import it.sw.pa.comune.artegna.service.StrutturaService;
import it.sw.pa.comune.artegna.service.criteria.StrutturaCriteria;
import it.sw.pa.comune.artegna.service.dto.StrutturaDTO;
import it.sw.pa.comune.artegna.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.PaginationUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link it.sw.pa.comune.artegna.domain.Struttura}.
 */
@RestController
@RequestMapping("/api/strutturas")
public class StrutturaResource {

    private static final Logger LOG = LoggerFactory.getLogger(StrutturaResource.class);

    private static final String ENTITY_NAME = "struttura";

    @Value("${jhipster.clientApp.name:smartbooking}")
    private String applicationName;

    private final StrutturaService strutturaService;

    private final StrutturaRepository strutturaRepository;

    private final StrutturaQueryService strutturaQueryService;

    public StrutturaResource(
        StrutturaService strutturaService,
        StrutturaRepository strutturaRepository,
        StrutturaQueryService strutturaQueryService
    ) {
        this.strutturaService = strutturaService;
        this.strutturaRepository = strutturaRepository;
        this.strutturaQueryService = strutturaQueryService;
    }

    /**
     * {@code POST  /strutturas} : Create a new struttura.
     *
     * @param strutturaDTO the strutturaDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new strutturaDTO, or with status {@code 400 (Bad Request)} if the struttura has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("")
    public ResponseEntity<StrutturaDTO> createStruttura(@RequestBody StrutturaDTO strutturaDTO) throws URISyntaxException {
        LOG.debug("REST request to save Struttura : {}", strutturaDTO);
        if (strutturaDTO.getId() != null) {
            throw new BadRequestAlertException("A new struttura cannot already have an ID", ENTITY_NAME, "idexists");
        }
        strutturaDTO = strutturaService.save(strutturaDTO);
        return ResponseEntity.created(new URI("/api/strutturas/" + strutturaDTO.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, strutturaDTO.getId().toString()))
            .body(strutturaDTO);
    }

    /**
     * {@code PUT  /strutturas/:id} : Updates an existing struttura.
     *
     * @param id the id of the strutturaDTO to save.
     * @param strutturaDTO the strutturaDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated strutturaDTO,
     * or with status {@code 400 (Bad Request)} if the strutturaDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the strutturaDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/{id}")
    public ResponseEntity<StrutturaDTO> updateStruttura(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody StrutturaDTO strutturaDTO
    ) throws URISyntaxException {
        LOG.debug("REST request to update Struttura : {}, {}", id, strutturaDTO);
        if (strutturaDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, strutturaDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!strutturaRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        strutturaDTO = strutturaService.update(strutturaDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, strutturaDTO.getId().toString()))
            .body(strutturaDTO);
    }

    /**
     * {@code PATCH  /strutturas/:id} : Partial updates given fields of an existing struttura, field will ignore if it is null
     *
     * @param id the id of the strutturaDTO to save.
     * @param strutturaDTO the strutturaDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated strutturaDTO,
     * or with status {@code 400 (Bad Request)} if the strutturaDTO is not valid,
     * or with status {@code 404 (Not Found)} if the strutturaDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the strutturaDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
    public ResponseEntity<StrutturaDTO> partialUpdateStruttura(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody StrutturaDTO strutturaDTO
    ) throws URISyntaxException {
        LOG.debug("REST request to partial update Struttura partially : {}, {}", id, strutturaDTO);
        if (strutturaDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, strutturaDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!strutturaRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<StrutturaDTO> result = strutturaService.partialUpdate(strutturaDTO);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, strutturaDTO.getId().toString())
        );
    }

    /**
     * {@code GET  /strutturas} : get all the strutturas.
     *
     * @param pageable the pagination information.
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of strutturas in body.
     */
    @GetMapping("")
    public ResponseEntity<List<StrutturaDTO>> getAllStrutturas(
        StrutturaCriteria criteria,
        @org.springdoc.core.annotations.ParameterObject Pageable pageable
    ) {
        LOG.debug("REST request to get Strutturas by criteria: {}", criteria);

        Page<StrutturaDTO> page = strutturaQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * {@code GET  /strutturas/count} : count all the strutturas.
     *
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
     */
    @GetMapping("/count")
    public ResponseEntity<Long> countStrutturas(StrutturaCriteria criteria) {
        LOG.debug("REST request to count Strutturas by criteria: {}", criteria);
        return ResponseEntity.ok().body(strutturaQueryService.countByCriteria(criteria));
    }

    /**
     * {@code GET  /strutturas/:id} : get the "id" struttura.
     *
     * @param id the id of the strutturaDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the strutturaDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<StrutturaDTO> getStruttura(@PathVariable("id") Long id) {
        LOG.debug("REST request to get Struttura : {}", id);
        Optional<StrutturaDTO> strutturaDTO = strutturaService.findOne(id);
        return ResponseUtil.wrapOrNotFound(strutturaDTO);
    }

    /**
     * {@code DELETE  /strutturas/:id} : delete the "id" struttura.
     *
     * @param id the id of the strutturaDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStruttura(@PathVariable("id") Long id) {
        LOG.debug("REST request to delete Struttura : {}", id);
        strutturaService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
