package com.oguerreiro.resilient.web.rest;

import com.oguerreiro.resilient.repository.OrganizationTypeRepository;
import com.oguerreiro.resilient.service.OrganizationTypeService;
import com.oguerreiro.resilient.service.dto.OrganizationTypeDTO;
import com.oguerreiro.resilient.web.rest.errors.BadRequestAlertException;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
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.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link com.oguerreiro.resilient.domain.OrganizationType}.
 */
@RestController
@RequestMapping("/api/organization-types")
public class OrganizationTypeResource {

    private final Logger log = LoggerFactory.getLogger(OrganizationTypeResource.class);

    private static final String ENTITY_NAME = "organizationType";

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

    private final OrganizationTypeService organizationTypeService;

    private final OrganizationTypeRepository organizationTypeRepository;

    public OrganizationTypeResource(
        OrganizationTypeService organizationTypeService,
        OrganizationTypeRepository organizationTypeRepository
    ) {
        this.organizationTypeService = organizationTypeService;
        this.organizationTypeRepository = organizationTypeRepository;
    }

    /**
     * {@code POST  /organization-types} : Create a new organizationType.
     *
     * @param organizationTypeDTO the organizationTypeDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new organizationTypeDTO, or with status {@code 400 (Bad Request)} if the organizationType has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("")
    public ResponseEntity<OrganizationTypeDTO> createOrganizationType(@Valid @RequestBody OrganizationTypeDTO organizationTypeDTO)
        throws URISyntaxException {
        log.debug("REST request to save OrganizationType : {}", organizationTypeDTO);
        if (organizationTypeDTO.getId() != null) {
            throw new BadRequestAlertException("A new organizationType cannot already have an ID", ENTITY_NAME, "idexists");
        }
        organizationTypeDTO = organizationTypeService.save(organizationTypeDTO);
        return ResponseEntity.created(new URI("/api/organization-types/" + organizationTypeDTO.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, organizationTypeDTO.getId().toString()))
            .body(organizationTypeDTO);
    }

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

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

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

    /**
     * {@code PATCH  /organization-types/:id} : Partial updates given fields of an existing organizationType, field will ignore if it is null
     *
     * @param id the id of the organizationTypeDTO to save.
     * @param organizationTypeDTO the organizationTypeDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated organizationTypeDTO,
     * or with status {@code 400 (Bad Request)} if the organizationTypeDTO is not valid,
     * or with status {@code 404 (Not Found)} if the organizationTypeDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the organizationTypeDTO 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<OrganizationTypeDTO> partialUpdateOrganizationType(
        @PathVariable(value = "id", required = false) final Long id,
        @NotNull @RequestBody OrganizationTypeDTO organizationTypeDTO
    ) throws URISyntaxException {
        log.debug("REST request to partial update OrganizationType partially : {}, {}", id, organizationTypeDTO);
        if (organizationTypeDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, organizationTypeDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

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

        Optional<OrganizationTypeDTO> result = organizationTypeService.partialUpdate(organizationTypeDTO);

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

    /**
     * {@code GET  /organization-types} : get all the organizationTypes.
     *
     * @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of organizationTypes in body.
     */
    @GetMapping("")
    public List<OrganizationTypeDTO> getAllOrganizationTypes(
        @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
    ) {
        log.debug("REST request to get all OrganizationTypes");
        return organizationTypeService.findAll();
    }

    /**
     * {@code GET  /organization-types/:id} : get the "id" organizationType.
     *
     * @param id the id of the organizationTypeDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the organizationTypeDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<OrganizationTypeDTO> getOrganizationType(@PathVariable("id") Long id) {
        log.debug("REST request to get OrganizationType : {}", id);
        Optional<OrganizationTypeDTO> organizationTypeDTO = organizationTypeService.findOne(id);
        return ResponseUtil.wrapOrNotFound(organizationTypeDTO);
    }

    /**
     * {@code DELETE  /organization-types/:id} : delete the "id" organizationType.
     *
     * @param id the id of the organizationTypeDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteOrganizationType(@PathVariable("id") Long id) {
        log.debug("REST request to delete OrganizationType : {}", id);
        organizationTypeService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
