package io.gmss.fiscad.controllers.decoupage;


import io.gmss.fiscad.entities.decoupage.Quartier;
import io.gmss.fiscad.exceptions.*;
import io.gmss.fiscad.interfaces.decoupage.QuartierService;
import io.gmss.fiscad.paylaods.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;


@RestController
@RequestMapping(value = "api/quartier", produces = MediaType.APPLICATION_JSON_VALUE)
@SecurityRequirement(name = "bearer")
@Tag(name = "Quartier")
@CrossOrigin(origins = "*")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_SUPERVISEUR')")
public class QuartierController {

    private final QuartierService quartierService;
    private static final Logger logger = LoggerFactory.getLogger(QuartierController.class);

    public QuartierController(QuartierService quartierService) {
        this.quartierService = quartierService;
    }

    @PostMapping("/create")
    public ResponseEntity<?> createQuartier(@RequestBody @Valid @Validated Quartier quartier) {
        try {
            quartier = quartierService.createQuartier(quartier);
            return new ResponseEntity<>(
                    new ApiResponse<>(true, quartier, "Quartier créé avec  succès."),
                    HttpStatus.OK
            );
        } catch (HttpClientErrorException.MethodNotAllowed e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Method POST/GET is required."), HttpStatus.OK);
        } catch (NotFoundException | BadRequestException | MyFileNotFoundException | ResourceNotFoundException |
                 FileStorageException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, e.getMessage()), HttpStatus.OK);
        } catch (NullPointerException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Null value has been detected {" + e.getMessage() + "}."), HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "An error has been occur and the content is {" + e.getMessage() + "}."), HttpStatus.OK);
        }
    }

    @PutMapping("/update/{id}")
    public ResponseEntity<?> updateQuartier(@PathVariable Long id, @RequestBody Quartier quartier) {
        try {
            return new ResponseEntity<>(
                    new ApiResponse<>(true, quartierService.updateQuartier(id, quartier), "Quartier mis à jour avec succès."),
                    HttpStatus.OK
            );
        } catch (HttpClientErrorException.MethodNotAllowed e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Method POST/GET is required."), HttpStatus.OK);
        } catch (NotFoundException | BadRequestException | MyFileNotFoundException | ResourceNotFoundException |
                 FileStorageException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, e.getMessage()), HttpStatus.OK);
        } catch (NullPointerException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Null value has been detected {" + e.getMessage() + "}."), HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "An error has been occur and the content is {" + e.getMessage() + "}."), HttpStatus.OK);
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> deleteQuartier(@PathVariable Long id) {
        try {
            quartierService.deleteQuartier(id);
            return new ResponseEntity<>(
                    new ApiResponse<>(true, "Quartier supprimé avec succès."),
                    HttpStatus.OK
            );
        } catch (HttpClientErrorException.MethodNotAllowed e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Method POST/GET is required."), HttpStatus.OK);
        } catch (NotFoundException | BadRequestException | MyFileNotFoundException | ResourceNotFoundException |
                 FileStorageException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, e.getMessage()), HttpStatus.OK);
        } catch (NullPointerException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Null value has been detected {" + e.getMessage() + "}."), HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "An error has been occur and the content is {" + e.getMessage() + "}."), HttpStatus.OK);
        }
    }

    @GetMapping("/all")
    public ResponseEntity<?> getAllQuartierList() {
        try {
            return new ResponseEntity<>(
                    new ApiResponse<>(true, quartierService.getQuartierList(), "Liste des quartiers chargée avec succès."),
                    HttpStatus.OK
            );
        } catch (HttpClientErrorException.MethodNotAllowed e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Method POST/GET is required."), HttpStatus.OK);
        } catch (NotFoundException | BadRequestException | MyFileNotFoundException | ResourceNotFoundException |
                 FileStorageException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, e.getMessage()), HttpStatus.OK);
        } catch (NullPointerException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Null value has been detected {" + e.getMessage() + "}."), HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "An error has been occur and the content is {" + e.getMessage() + "}."), HttpStatus.OK);
        }
    }

    @GetMapping("/all-paged")
    public ResponseEntity<?> getAllQuartierPaged(@RequestParam int pageNo, @RequestParam int pageSize) {
        try {
            Pageable pageable = PageRequest.of(pageNo, pageSize);
            return new ResponseEntity<>(
                    new ApiResponse<>(true, quartierService.getQuartierList(pageable), "Liste des quartiers chargée avec succès."),
                    HttpStatus.OK
            );
        } catch (HttpClientErrorException.MethodNotAllowed e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Method POST/GET is required."), HttpStatus.OK);
        } catch (NotFoundException | BadRequestException | MyFileNotFoundException | ResourceNotFoundException |
                 FileStorageException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, e.getMessage()), HttpStatus.OK);
        } catch (NullPointerException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Null value has been detected {" + e.getMessage() + "}."), HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "An error has been occur and the content is {" + e.getMessage() + "}."), HttpStatus.OK);
        }
    }

    @GetMapping("/id/{id}")
    public ResponseEntity<?> getQuartierById(@PathVariable Long id) {
        try {
            return new ResponseEntity<>(
                    new ApiResponse<>(true, quartierService.getQuartierById(id), "Quartier trouvé avec succès."),
                    HttpStatus.OK
            );
        } catch (HttpClientErrorException.MethodNotAllowed e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Method POST/GET is required."), HttpStatus.OK);
        } catch (NotFoundException | BadRequestException | MyFileNotFoundException | ResourceNotFoundException |
                 FileStorageException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, e.getMessage()), HttpStatus.OK);
        } catch (NullPointerException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Null value has been detected {" + e.getMessage() + "}."), HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "An error has been occur and the content is {" + e.getMessage() + "}."), HttpStatus.OK);
        }
    }

    @GetMapping("/arrondissement/{arrondissementId}")
    public ResponseEntity<?> getQuartierByArrondissement(@PathVariable Long arrondissementId) {

        try {
            return new ResponseEntity<>(
                    new ApiResponse<>(true, quartierService.getQuartierByArrondissement(arrondissementId), "Liste des quartiers par commune chargée avec succès."),
                    HttpStatus.OK
            );
        } catch (HttpClientErrorException.MethodNotAllowed e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Method POST/GET is required."), HttpStatus.OK);
        } catch (NotFoundException | BadRequestException | MyFileNotFoundException | ResourceNotFoundException |
                 FileStorageException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, e.getMessage()), HttpStatus.OK);
        } catch (NullPointerException e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "Null value has been detected {" + e.getMessage() + "}."), HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            return new ResponseEntity<>(new ApiResponse(false, null, "An error has been occur and the content is {" + e.getMessage() + "}."), HttpStatus.OK);
        }
    }
}
