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.violation.*;
import ru.soune.nocopy.entity.user.AuthToken;
import ru.soune.nocopy.repository.AuthTokenRepository;
import ru.soune.nocopy.service.violation.ViolationNotionService;

import java.util.Optional;

@Slf4j
@Component
@RequiredArgsConstructor
public class ViolationNotionHandler implements RequestHandler {
    private final ObjectMapper objectMapper;

    private final ViolationNotionService notionService;

    private final AuthTokenRepository authTokenRepository;

    @Override
    public BaseResponse handle(BaseRequest request) {
        try {
            ViolationNotionRequest notionRequest = objectMapper.convertValue(
                    request.getMessageBody(), ViolationNotionRequest.class);

            if (notionRequest.getToken() == null) {
                return new BaseResponse(
                        request.getMsgId(),
                        MessageCode.INVALID_TOKEN.getCode(),
                        "Token is required",
                        null);
            }

            Optional<AuthToken> tokenOptional = authTokenRepository.findByToken(notionRequest.getToken());
            if (tokenOptional.isEmpty()) {
                return new BaseResponse(
                        request.getMsgId(),
                        MessageCode.INVALID_TOKEN.getCode(),
                        "Invalid token",
                        null);
            }

            Long userId = tokenOptional.get().getUser().getId();
            String action = notionRequest.getAction();

            if (action == null || action.trim().isEmpty()) {
                return new BaseResponse(
                        request.getMsgId(),
                        MessageCode.INVALID_ACTION.getCode(),
                        "Action is required",
                        null);
            }

            switch (action) {
                case "get_notions":
                    return handleGetNotions(request, notionRequest, userId);
                case "get_notion":
                    return handleGetNotion(request, notionRequest, userId);
                case "add_notion":
                    return handleAddNotion(request, notionRequest, userId);
                case "update_notion":
                    return handleUpdateNotion(request, notionRequest, userId);
                case "delete_notion":
                    return handleDeleteNotion(request, notionRequest, userId);
                default:
                    return new BaseResponse(
                            request.getMsgId(),
                            MessageCode.INVALID_ACTION.getCode(),
                            "Invalid action: " + action,
                            null);
            }

        } catch (IllegalArgumentException e) {
            log.error("Validation error: {}", e.getMessage());
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.VALIDATION_ERROR.getCode(),
                    e.getMessage(),
                    null);
        } catch (SecurityException e) {
            log.error("Security error: {}", e.getMessage());
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.ACCESS_DENIED.getCode(),
                    e.getMessage(),
                    null);
        } catch (Exception e) {
            log.error("Unexpected error", e);
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.INTERNAL_ERROR.getCode(),
                    "Internal server error",
                    null);
        }
    }

    private BaseResponse handleGetNotions(BaseRequest request, ViolationNotionRequest notionRequest, Long userId) {
        if (notionRequest.getViolationId() == null) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.INVALID_JSON_BODY.getCode(),
                    "ViolationId is required for get_notions action",
                    null);
        }

        try {
            ViolationNotionsListResponse notions = notionService.getNotionsByViolationId(
                    notionRequest.getViolationId(), userId);
            return BaseResponse.builder()
                    .msgId(request.getMsgId())
                    .messageBody(notions)
                    .build();
        } catch (IllegalArgumentException e) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.NOTION_NOT_FOUND.getCode(),
                    e.getMessage(),
                    null);
        }
    }

    private BaseResponse handleGetNotion(BaseRequest request, ViolationNotionRequest notionRequest, Long userId) {
        if (notionRequest.getNotionId() == null) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.INVALID_JSON_BODY.getCode(),
                    "NotionId is required for get_notion action",
                    null);
        }

        try {
            ViolationNotionResponse notion = notionService.getNotionById(
                    notionRequest.getNotionId(), userId);
            return BaseResponse.builder()
                    .msgId(request.getMsgId())
                    .messageBody(notion)
                    .build();
        } catch (IllegalArgumentException e) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.NOTION_NOT_FOUND.getCode(),
                    e.getMessage(),
                    null);
        }
    }

    private BaseResponse handleAddNotion(BaseRequest request, ViolationNotionRequest notionRequest, Long userId) {
        if (notionRequest.getViolationId() == null) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.INVALID_JSON_BODY.getCode(),
                    "ViolationId is required for add_notion action",
                    null);
        }

        if (notionRequest.getMessage() == null || notionRequest.getMessage().trim().isEmpty()) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.INVALID_JSON_BODY.getCode(),
                    "Message is required for add_notion action",
                    null);
        }

        try {
            ViolationNotionResponse created = notionService.createNotion(
                    notionRequest.getViolationId(), userId, notionRequest.getMessage());
            return BaseResponse.builder()
                    .msgId(request.getMsgId())
                    .messageBody(created)
                    .build();
        } catch (IllegalArgumentException e) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.NOTION_NOT_FOUND.getCode(),
                    e.getMessage(),
                    null);
        }
    }

    private BaseResponse handleUpdateNotion(BaseRequest request, ViolationNotionRequest notionRequest, Long userId) {
        if (notionRequest.getNotionId() == null) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.INVALID_JSON_BODY.getCode(),
                    "NotionId is required for update_notion action",
                    null);
        }

        if (notionRequest.getMessage() == null || notionRequest.getMessage().trim().isEmpty()) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.INVALID_JSON_BODY.getCode(),
                    "Message is required for update_notion action",
                    null);
        }

        try {
            ViolationNotionResponse updated = notionService.updateNotion(
                    notionRequest.getNotionId(), userId, notionRequest.getMessage());
            return BaseResponse.builder()
                    .msgId(request.getMsgId())
                    .messageBody(updated)
                    .build();
        } catch (IllegalArgumentException e) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.NOTION_NOT_FOUND.getCode(),
                    e.getMessage(),
                    null);
        } catch (SecurityException e) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.ACCESS_DENIED.getCode(),
                    e.getMessage(),
                    null);
        }
    }

    private BaseResponse handleDeleteNotion(BaseRequest request, ViolationNotionRequest notionRequest, Long userId) {
        if (notionRequest.getNotionId() == null) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.INVALID_JSON_BODY.getCode(),
                    "NotionId is required for delete_notion action",
                    null);
        }

        try {
            notionService.deleteNotion(notionRequest.getNotionId(), userId);
            DeleteNotionResponse deleteResponse = DeleteNotionResponse.builder()
                    .notionId(notionRequest.getNotionId())
                    .message("Notion deleted successfully")
                    .deleted(true)
                    .build();
            return BaseResponse.builder()
                    .msgId(request.getMsgId())
                    .messageBody(deleteResponse)
                    .build();
        } catch (IllegalArgumentException e) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.NOTION_NOT_FOUND.getCode(),
                    e.getMessage(),
                    null);
        } catch (SecurityException e) {
            return new BaseResponse(
                    request.getMsgId(),
                    MessageCode.ACCESS_DENIED.getCode(),
                    e.getMessage(),
                    null);
        }
    }
}
