package ru.soune.nocopy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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.entity.user.User;
import ru.soune.nocopy.repository.ComplaintEntityRepository;
import ru.soune.nocopy.repository.FileEntityRepository;
import ru.soune.nocopy.repository.UserRepository;
import ru.soune.nocopy.service.complaint.ComplaintEntityService;
import ru.soune.nocopy.service.register.AuthService;
import ru.soune.nocopy.service.user.UserService;

import java.util.*;

@Slf4j
@Component
@RequiredArgsConstructor
public class ComplaintEntityHandler implements RequestHandler {
    private final ComplaintEntityService complaintService;

    private final ObjectMapper objectMapper;

    private final UserRepository userRepository;

    private final UserService userService;

    private final AuthService authService;

    private final FileEntityRepository fileEntityRepository;

    private final ComplaintEntityRepository complaintEntityRepository;

    @Override
    public BaseResponse handle(BaseRequest request) throws Exception {
        Integer msgId = request.getMsgId();
        ComplaintRequest complaintRequest = objectMapper.convertValue(request.getMessageBody(), ComplaintRequest.class);
        String action = complaintRequest.getAction() == null ? "" : complaintRequest.getAction();
        String token = complaintRequest.getToken();
        Long userId = authService.useUserAuthToken(token);
        User user = userRepository.findById(userId).orElse(null);

        if (user == null) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.USER_NOT_FOUND.getCode(),
                    MessageCode.USER_NOT_FOUND.getDescription(),
                    Map.of("token: ", token));
        }

        List<String> emails = user.getCompany() == null ? List.of(user.getEmail()):
                userService.getUsersCompanyEmails(user.getCompany().getId());

        try {
            return switch (action) {
                case "create" -> handleCreate(msgId, complaintRequest, userId);
                case "get" -> handleGet(msgId, complaintRequest, userId);
                case "get_all" -> handleGetAll(msgId, complaintRequest, emails);
                case "get_by_violation" -> handleGetByViolation(msgId, complaintRequest, userId);
                case "update_status" -> handleUpdateStatus(msgId, complaintRequest, userId);
                case "update" -> handleUpdate(msgId, complaintRequest, userId);
                case "delete" -> handleDelete(msgId, complaintRequest);
                default -> errorResponse(msgId, MessageCode.MSG_ID_NOT_FOUND.getCode(), "Valid actions: " +
                        List.of("create", "get", "get_all", "get_by_violation", "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 handleCreate(Integer msgId, ComplaintRequest req, Long userId) {
        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");

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

        if (complaintEntity == null || !Objects.equals(
                complaintEntity.getViolation().getFileEntity().getUserId(), userId)) {
            return errorResponse(msgId, MessageCode.USER_NOT_HAD_PERMISSION.getCode(),
                    MessageCode.USER_NOT_HAD_PERMISSION.getDescription());
        }

        ComplaintResponse response = complaintService.createComplaint(req);

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

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

        ComplaintResponse response = complaintService.getComplaintById(req.getId());

        if (!Objects.equals(fileEntityRepository.findByFileId(response.getFileId()).getUserId(), userId)) {
            return errorResponse(msgId, MessageCode.USER_NOT_HAD_PERMISSION.getCode(),
                    "User not have permission for file");
        }

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

    private BaseResponse handleGetAll(Integer msgId, ComplaintRequest req, List<String> emails) {
        Pageable pageable = PageRequest.of(
                req.getPage() != null ? req.getPage() : 0,
                req.getSize() != null ? req.getSize() : 5,
                Sort.by(Sort.Direction.fromString(
                                req.getSortDirection() != null ? req.getSortDirection() : "desc"),
                        req.getSortBy() != null ? req.getSortBy() : "updatedAt"));

        var page = complaintService.getAllComplaintsByEmail(pageable, emails);

        Map<String, Object> data = new HashMap<>();
        data.put("content", page.getContent());
        data.put("page", page.getNumber() + 1);
        data.put("size", page.getSize());
        data.put("totalElements", page.getTotalElements());
        data.put("totalPages", page.getTotalPages());

        return successResponse(msgId, "Complaints retrieved successfully", data);
    }

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

        ComplaintResponse response = complaintService.getComplaintsByViolationId(req.getViolationId());

        if (!Objects.equals(fileEntityRepository.findByFileId(response.getFileId()).getUserId(), userId)) {
            return errorResponse(msgId, MessageCode.USER_NOT_HAD_PERMISSION.getCode(),
                    "User not have permission for file");
        }

        return successResponse(msgId, "Complaints retrieved successfully", response);
    }

    private BaseResponse handleUpdateStatus(Integer msgId, ComplaintRequest req, Long userId) {
        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 || !Objects.equals(
                complaintEntity.getViolation().getFileEntity().getUserId(), userId)) {
            return errorResponse(msgId, MessageCode.USER_NOT_HAD_PERMISSION.getCode(),
                    MessageCode.USER_NOT_HAD_PERMISSION.getDescription());
        }

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

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

    private BaseResponse handleUpdate(Integer msgId, ComplaintRequest req, Long userId) {
        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 || !Objects.equals(
                complaintEntity.getViolation().getFileEntity().getUserId(), userId)) {
            return errorResponse(msgId, MessageCode.USER_NOT_HAD_PERMISSION.getCode(),
                    MessageCode.USER_NOT_HAD_PERMISSION.getDescription());
        }

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

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

    private BaseResponse handleDelete(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<>());
    }
}
