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

import it.sw.pa.comune.artegna.domain.User;
import it.sw.pa.comune.artegna.repository.UtenteAppRepository;
import it.sw.pa.comune.artegna.security.SecurityUtils;
import it.sw.pa.comune.artegna.service.UserService;
import it.sw.pa.comune.artegna.service.UtenteAppService;
import it.sw.pa.comune.artegna.service.dto.UserDTO;
import it.sw.pa.comune.artegna.service.dto.UtenteAppDTO;
import it.sw.pa.comune.artegna.service.mapper.UserMapper;
import it.sw.pa.comune.artegna.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.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link it.sw.pa.comune.artegna.domain.UtenteApp}.
 */
@RestController
@RequestMapping("/api/utente-apps")
public class UtenteAppResource {

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

    private static final String ENTITY_NAME = "utenteApp";

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

    private final UtenteAppService utenteAppService;

    private final UtenteAppRepository utenteAppRepository;

    private final UserService userService;

    private final UserMapper userMapper;

    public UtenteAppResource(
        UtenteAppService utenteAppService,
        UtenteAppRepository utenteAppRepository,
        UserService userService,
        UserMapper userMapper
    ) {
        this.utenteAppService = utenteAppService;
        this.utenteAppRepository = utenteAppRepository;
        this.userService = userService;
        this.userMapper = userMapper;
    }

    /**
     * {@code POST  /utente-apps} : Create a new utenteApp.
     *
     * @param utenteAppDTO the utenteAppDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new utenteAppDTO, or with status {@code 400 (Bad Request)} if the utenteApp has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("")
    public ResponseEntity<UtenteAppDTO> createUtenteApp(
        @Valid @RequestBody UtenteAppDTO utenteAppDTO,
        @AuthenticationPrincipal UserDetails principal
    ) throws URISyntaxException {
        LOG.debug("REST request to save UtenteApp : {}", utenteAppDTO);
        if (utenteAppDTO.getId() != null) {
            throw new BadRequestAlertException("A new utenteApp cannot already have an ID", ENTITY_NAME, "idexists");
        }

        utenteAppDTO = utenteAppService.save(utenteAppDTO);
        return ResponseEntity.created(new URI("/api/utente-apps/" + utenteAppDTO.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, utenteAppDTO.getId().toString()))
            .body(utenteAppDTO);
    }

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

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

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

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

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

        Optional<UtenteAppDTO> result = utenteAppService.partialUpdate(utenteAppDTO);

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

    /**
     * {@code GET  /utente-apps} : get all the utenteApps.
     *
     * @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 utenteApps in body.
     */
    @GetMapping("")
    public List<UtenteAppDTO> getAllUtenteApps(
        @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
    ) {
        LOG.debug("REST request to get all UtenteApps");
        return utenteAppService.findAll();
    }

    /**
     * {@code GET  /utente-apps/:id} : get the "id" utenteApp.
     *
     * @param id the id of the utenteAppDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the utenteAppDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<UtenteAppDTO> getUtenteApp(@PathVariable("id") Long id) {
        LOG.debug("REST request to get UtenteApp : {}", id);
        Optional<UtenteAppDTO> utenteAppDTO = utenteAppService.findOne(id);
        return ResponseUtil.wrapOrNotFound(utenteAppDTO);
    }

    @GetMapping("/current")
    public ResponseEntity<UtenteAppDTO> getCurrentUser() {
        LOG.debug("REST request to get current user");

        return SecurityUtils.getCurrentUserLogin()
            .flatMap(utenteAppService::findByUsername)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    /**
     * {@code POST  /utente-apps/current} : Create or update the current user's profile.
     *
     * @param utenteAppDTO the utenteAppDTO to save.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated utenteAppDTO.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/current")
    public ResponseEntity<UtenteAppDTO> saveCurrentUserProfile(
        @Valid @RequestBody UtenteAppDTO utenteAppDTO,
        @AuthenticationPrincipal UserDetails principal
    ) throws URISyntaxException {
        LOG.debug("REST request to save current user profile : {}", utenteAppDTO);

        String currentUserLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() ->
            new BadRequestAlertException("Current user login not found", ENTITY_NAME, "usernotfound")
        );

        // Ensure the username matches the current user
        utenteAppDTO.setUsername(currentUserLogin);

        UtenteAppDTO result;
        if (utenteAppDTO.getId() != null) {
            // Update existing profile
            result = utenteAppService.update(utenteAppDTO);
        } else {
            // collect current user login infos
            String currentLogin = principal.getUsername();
            User currentUser = userService.getUserWithAuthoritiesByLogin(currentLogin).orElseThrow();
            utenteAppDTO.setInternalUser(userMapper.userToUserDTO(currentUser));
            // Create new profile
            result = utenteAppService.save(utenteAppDTO);
        }

        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code DELETE  /utente-apps/:id} : delete the "id" utenteApp.
     *
     * @param id the id of the utenteAppDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUtenteApp(@PathVariable("id") Long id) {
        LOG.debug("REST request to delete UtenteApp : {}", id);
        utenteAppService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
