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.ComplaintStatus;
import ru.soune.nocopy.service.complaint.ComplaintEntityService;
import java.util.HashMap;
import java.util.Map;

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

    private final ObjectMapper objectMapper;

    @Override
    public BaseResponse handle(BaseRequest request) throws Exception {
        Integer msgId = request.getMsgId();
        ComplaintRequest complaintRequest = objectMapper.convertValue(request.getMessageBody(), ComplaintRequest.class);
        String action = complaintRequest.getAction();

        try {
            switch (action.toLowerCase()) {
                case "create":
                    return handleCreate(msgId, complaintRequest);
                case "get":
                    return handleGet(msgId, complaintRequest);
                case "get_all":
                    return handleGetAll(msgId, complaintRequest);
                case "get_by_violation":
                    return handleGetByViolation(msgId, complaintRequest);
                case "update_status":
                    return handleUpdateStatus(msgId, complaintRequest);
                case "update":
                    return handleUpdate(msgId, complaintRequest);
                case "delete":
                    return handleDelete(msgId, complaintRequest);
                default:
                    return errorResponse(msgId, MessageCode.MSG_ID_NOT_FOUND.getCode(), "Unknown action: " + action);
            }
        } 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) {
        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");

        ComplaintResponse response = complaintService.createComplaint(req);

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

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

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

    private BaseResponse handleGetAll(Integer msgId, ComplaintRequest req) {
        Pageable pageable = PageRequest.of(
                req.getPage() != null ? req.getPage() : 0,
                req.getSize() != null ? req.getSize() : 20,
                Sort.by(Sort.Direction.fromString(req.getSortDirection() != null ? req.getSortDirection() : "desc"),
                        req.getSortBy() != null ? req.getSortBy() : "createdAt")
        );

        var page = complaintService.getAllComplaints(pageable);
        Map<String, Object> data = new HashMap<>();
        data.put("content", page.getContent());
        data.put("page", page.getNumber());
        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) {
        if (req.getViolationId() == null) return errorResponse(msgId, MessageCode.NOT_FOUND.getCode(),
                "violation_id is required");

        var complaints = complaintService.getComplaintsByViolationId(req.getViolationId());
        Map<String, Object> data = new HashMap<>();
        data.put("content", complaints);
        data.put("totalElements", complaints.size());

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

    private BaseResponse handleUpdateStatus(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");

        ComplaintStatus status = ComplaintStatus.valueOf(req.getStatus().toUpperCase());
        ComplaintResponse response = complaintService.updateComplaintStatus(req.getId(), status);
        return successResponse(msgId, "Status updated successfully", response);
    }

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

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