package io.gmss.fiscad.controllers.rfu.metier;


import io.gmss.fiscad.entities.rfu.metier.DonneesImpositionTfu;
import io.gmss.fiscad.entities.rfu.metier.ImpositionsTfu;
import io.gmss.fiscad.enums.StatusAvis;
import io.gmss.fiscad.exceptions.*;
import io.gmss.fiscad.interfaces.rfu.metier.DonneesImpositionTfuService;
import io.gmss.fiscad.paylaods.ApiResponse;
import io.gmss.fiscad.repositories.rfu.metier.ImpositionsTfuRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;

import java.util.Optional;


@RestController
@RequestMapping(value = "api/donnees-impositions-tfu", produces = MediaType.APPLICATION_JSON_VALUE)
@SecurityRequirement(name = "bearer")
@Tag(name = "DonneesImpositionTfu")
@CrossOrigin(origins = "*")
@AllArgsConstructor
public class DonneesImpositionTfuController {

    private final DonneesImpositionTfuService donneesImpositionTfuService ;
    private final ImpositionsTfuRepository impositionsTfuRepository ;

    private static final Logger logger = LoggerFactory.getLogger(DonneesImpositionTfuController.class);



    @PostMapping("/create")
    public ResponseEntity<?> createDonneesImpositionTfu(@RequestBody @Valid @Validated DonneesImpositionTfu donneesImpositionTfu) {
        try {
            donneesImpositionTfu = donneesImpositionTfuService.createDonneesImpositionTfu(donneesImpositionTfu);
            return new ResponseEntity<>(
                    new ApiResponse<>(true, donneesImpositionTfu, "DonneesImpositionTfu 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<?> updateDonneesImpositionTfu(@PathVariable Long id, @RequestBody DonneesImpositionTfu donneesImpositionTfu) {
        try {
            return new ResponseEntity<>(
                    new ApiResponse<>(true, donneesImpositionTfuService.updateDonneesImpositionTfu(id, donneesImpositionTfu), "DonneesImpositionTfu mise à 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<?> deleteDonneesImpositionTfu(@PathVariable Long id) {
        try {
            donneesImpositionTfuService.deleteDonneesImpositionTfu(id);
            return new ResponseEntity<>(
                    new ApiResponse<>(true, "DonneesImpositionTfu supprimé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")
    public ResponseEntity<?> getAllDonneesImpositionTfuList() {
        try {
            return new ResponseEntity<>(
                    new ApiResponse<>(true, donneesImpositionTfuService.getDonneesImpositionTfuList(), "Liste des caractéristiques 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<?> getAllDonneesImpositionTfuPaged(@RequestParam int pageNo, @RequestParam int pageSize) {
        try {
            Pageable pageable = PageRequest.of(pageNo, pageSize);
            return new ResponseEntity<>(
                    new ApiResponse<>(true, donneesImpositionTfuService.getDonneesImpositionTfuList(pageable), "Liste des caractéristiques 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<?> getDonneesImpositionTfuById(@PathVariable Long id) {
        try {
            return new ResponseEntity<>(
                    new ApiResponse<>(true, donneesImpositionTfuService.getDonneesImpositionTfuById(id), "DonneesImpositionTfu trouvé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);
        }
    }
    @Operation(summary = "Générer les données fiscales TFU")
    @PostMapping("/generer")
    public ResponseEntity<?> genererDonneesFiscale(@RequestBody ImpositionsTfu impositionsTfu) {
        try {
            Optional<ImpositionsTfu> optionalImpositionsTfu =impositionsTfuRepository.findById(impositionsTfu.getId());

            if(optionalImpositionsTfu.isEmpty()){
                return new ResponseEntity<>(
                        new ApiResponse<>(false, null, "L'imposition tfu n'est pas trouvée."),
                        HttpStatus.OK
                );
            }

            if(!optionalImpositionsTfu.get().getStatusAvis().equals(StatusAvis.CREE)){
                return new ResponseEntity<>(
                        new ApiResponse<>(false, null, "le statut actuel ne permet pas cette opération."),
                        HttpStatus.OK
                );
            }

            optionalImpositionsTfu.get().setStatusAvis(StatusAvis.GENERE);
            return new ResponseEntity<>(
                    new ApiResponse<>(true, donneesImpositionTfuService.genererDonneesFiscales(optionalImpositionsTfu.get()), "DonneesImpositionTfu trouvé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);
        }
    }

    @Operation(summary = "Récuperer les avis d'id d'une imposition")
    @GetMapping("/by-impositions-id/{impositionsId}")
    public ResponseEntity<?> getDonneesFiscale(@PathVariable Long impositionsId) {
        try {

            return new ResponseEntity<>(
                    new ApiResponse<>(true, donneesImpositionTfuService.getDonneesFiscalesByImposition(impositionsId), "DonneesImpositionTfu trouvé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);
        }
    }


    @Operation(summary = "Récuperer les avis d'id d'une imposition et l'id d'un arrondissement")
    @GetMapping("/by-impositions-id/by-arrondissement/{impositionsId}/{arrondissementId}")
    public ResponseEntity<?> getDonneesFiscaleParImpositionArrondissement(@PathVariable Long impositionsId,@PathVariable Long arrondissementId) {
        try {

            return new ResponseEntity<>(
                    new ApiResponse<>(true, donneesImpositionTfuService.getDonneesFiscalesByImpositionArrondissement(impositionsId,arrondissementId), "DonneesImpositionTfu trouvé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);
        }
    }
}
