package ru.soune.nocopy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import ru.soune.nocopy.dto.BaseRequest;
import ru.soune.nocopy.dto.BaseResponse;
import ru.soune.nocopy.dto.MessageCode;
import ru.soune.nocopy.dto.complaint.ComplaintRequest;
import ru.soune.nocopy.dto.complaint.ComplaintResponse;
import ru.soune.nocopy.entity.complaint.ComplaintEntity;
import ru.soune.nocopy.entity.complaint.ComplaintStatus;
import ru.soune.nocopy.repository.ComplaintEntityRepository;
import ru.soune.nocopy.service.complaint.ComplaintEntityService;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class ControlComplaintHandler implements RequestHandler{

    private final ObjectMapper objectMapper;

    private final ComplaintEntityRepository complaintEntityRepository;

    private final ComplaintEntityService complaintService;

    @Override
    public BaseResponse handle(BaseRequest request) throws Exception {
        ComplaintRequest complaintRequest = objectMapper.convertValue(request.getMessageBody(), ComplaintRequest.class);
        Integer msgId = request.getMsgId();
        log.info("start create complaint!");
        try {
            return switch (complaintRequest.getAction()) {
                case "update_status" -> updateStatus(msgId, complaintRequest);
                case "update" -> update(msgId, complaintRequest);
                case "delete" -> delete(msgId, complaintRequest);
                case "create" -> create(msgId, complaintRequest);
                default -> errorResponse(msgId, MessageCode.MSG_ID_NOT_FOUND.getCode(), "Valid actions: " +
                        List.of("create", "update_status", "update", "delete"));
            };
        } catch (Exception e) {
            log.error("Error handling complaint request", e);
            return errorResponse(msgId, MessageCode.INVALID_JSON_BODY.getCode(), e.getMessage());
        }
    }

    private BaseResponse create(Integer msgId, ComplaintRequest req) {
        if (req.getViolationId() == null) return errorResponse(msgId, MessageCode.NOT_FOUND.getCode(),
                "violation_id is required");
        if (req.getComplaintText() == null) return errorResponse(msgId, MessageCode.NOT_FOUND.getCode(),
                "text is required");
        Long violationId = req.getViolationId();

        if (complaintEntityRepository.existsByViolationId(violationId)) {
            return errorResponse(msgId, MessageCode.COMPLAINT_ALREADY_EXIST.getCode(),
                    MessageCode.COMPLAINT_ALREADY_EXIST.getDescription());
        }

        return successResponse(msgId, "Complaint created successfully", complaintService.createComplaint(req));
    }


    private BaseResponse updateStatus(Integer msgId, ComplaintRequest req) {
        if (req.getId() == null) return errorResponse(msgId, MessageCode.NOT_FOUND.getCode(), "id is required");
        if (req.getStatus() == null) return errorResponse(msgId, MessageCode.NOT_FOUND.getCode(), "status is required");

        List<String> statuses = Arrays.stream(ComplaintStatus.values()).map(ComplaintStatus::name).toList();

        if (statuses.stream().noneMatch(status -> status.equals(req.getStatus().toUpperCase()))) {
            return errorResponse(msgId, MessageCode.NOT_VALID_STATUS.getCode(), "Valid statuses: " + statuses);
        }

        ComplaintStatus status = ComplaintStatus.valueOf(req.getStatus().toUpperCase());

        ComplaintEntity complaintEntity = complaintEntityRepository.findById(req.getId()).orElse(null);

        if (complaintEntity == null) {
            return errorResponse(msgId, MessageCode.COMPLAINT_NOT_FOUND.getCode(),
                    MessageCode.COMPLAINT_NOT_FOUND.getDescription());
        }

        ComplaintResponse response = complaintService.updateComplaintStatus(complaintEntity, status);

        return successResponse(msgId, "Status updated successfully", response);
    }

    private BaseResponse update(Integer msgId, ComplaintRequest req) {
        if (req.getId() == null) return errorResponse(msgId, MessageCode.NOT_FOUND.getCode(), "id is required");

        ComplaintEntity complaintEntity = complaintEntityRepository.findById(req.getId()).orElse(null);

        if (complaintEntity == null) {
            return errorResponse(msgId, MessageCode.COMPLAINT_NOT_FOUND.getCode(),
                    MessageCode.COMPLAINT_NOT_FOUND.getDescription());
        }

        ComplaintResponse response = complaintService.updateComplaint(req.getId(), req);

        return successResponse(msgId, "Complaint updated successfully", response);
    }

    private BaseResponse delete(Integer msgId, ComplaintRequest req) {
        if (req.getId() == null) return errorResponse(msgId, MessageCode.NOT_FOUND.getCode(), "id is required");

        ComplaintResponse response = complaintService.deleteComplaint(req.getId());
        return successResponse(msgId, "Complaint deleted successfully", response);
    }

    private BaseResponse successResponse(Integer msgId, String message, Object data) {
        return new BaseResponse(msgId, MessageCode.SUCCESS.getCode(), message, data);
    }

    private BaseResponse errorResponse(Integer msgId, Integer code, String message) {
        return new BaseResponse(msgId, code, message, new HashMap<>());
    }
}
