package com.emonster.taroaichat.web.rest;

import com.emonster.taroaichat.repository.TarotCardRepository;
import com.emonster.taroaichat.service.TarotCardQueryService;
import com.emonster.taroaichat.service.TarotCardService;
import com.emonster.taroaichat.service.criteria.TarotCardCriteria;
import com.emonster.taroaichat.service.dto.TarotCardDTO;
import com.emonster.taroaichat.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.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 com.emonster.taroaichat.domain.TarotCard}.
 */
@RestController
@RequestMapping("/api/v1/tarot-cards")
public class TarotCardResource {

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

    private static final String ENTITY_NAME = "tarotCard";

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

    private final TarotCardService tarotCardService;

    private final TarotCardRepository tarotCardRepository;

    private final TarotCardQueryService tarotCardQueryService;

    public TarotCardResource(
        TarotCardService tarotCardService,
        TarotCardRepository tarotCardRepository,
        TarotCardQueryService tarotCardQueryService
    ) {
        this.tarotCardService = tarotCardService;
        this.tarotCardRepository = tarotCardRepository;
        this.tarotCardQueryService = tarotCardQueryService;
    }

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

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

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

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

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

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

        Optional<TarotCardDTO> result = tarotCardService.partialUpdate(tarotCardDTO);

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

    /**
     * {@code GET  /tarot-cards} : get all the tarotCards.
     *
     * @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 tarotCards in body.
     */
    @GetMapping("")
    public ResponseEntity<List<TarotCardDTO>> getAllTarotCards(
        TarotCardCriteria criteria,
        @org.springdoc.core.annotations.ParameterObject Pageable pageable
    ) {
        LOG.debug("REST request to get TarotCards by criteria: {}", criteria);

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

    /**
     * {@code GET  /tarot-cards/count} : count all the tarotCards.
     *
     * @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> countTarotCards(TarotCardCriteria criteria) {
        LOG.debug("REST request to count TarotCards by criteria: {}", criteria);
        return ResponseEntity.ok().body(tarotCardQueryService.countByCriteria(criteria));
    }

    /**
     * {@code GET  /tarot-cards/:id} : get the "id" tarotCard.
     *
     * @param id the id of the tarotCardDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the tarotCardDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<TarotCardDTO> getTarotCard(@PathVariable("id") Long id) {
        LOG.debug("REST request to get TarotCard : {}", id);
        Optional<TarotCardDTO> tarotCardDTO = tarotCardService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tarotCardDTO);
    }

    /**
     * {@code DELETE  /tarot-cards/:id} : delete the "id" tarotCard.
     *
     * @param id the id of the tarotCardDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTarotCard(@PathVariable("id") Long id) {
        LOG.debug("REST request to delete TarotCard : {}", id);
        tarotCardService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
