package com.caliverse.admin.dynamodb.repository.Impl;

import com.caliverse.admin.domain.request.WorldEventRequest;
import com.caliverse.admin.dynamodb.domain.atrrib.WorldEventScheduleAttrib;
import com.caliverse.admin.dynamodb.domain.doc.WorldEventScheduleDoc;
import com.caliverse.admin.dynamodb.entity.DynamodbOperationResult;
import com.caliverse.admin.dynamodb.repository.BaseDynamoDBRepository;
import com.caliverse.admin.dynamodb.repository.WorldEventScheduleRepository;
import com.caliverse.admin.dynamodb.service.DynamoDBOperations;
import com.caliverse.admin.global.common.code.CommonCode;
import com.caliverse.admin.global.common.code.ErrorCode;
import com.caliverse.admin.global.common.constants.DynamoDBConstants;
import com.caliverse.admin.global.common.exception.RestApiException;
import com.caliverse.admin.global.common.utils.CommonUtils;
import com.caliverse.admin.mongodb.service.DynamodbHistoryLogService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import software.amazon.awssdk.enhanced.dynamodb.Key;

import java.time.LocalDateTime;

import static com.caliverse.admin.global.common.utils.CommonUtils.convertUTCDate;

@Component
@Slf4j
public class WorldEventRepositoryImpl extends BaseDynamoDBRepository<WorldEventScheduleDoc> implements WorldEventScheduleRepository {
    public WorldEventRepositoryImpl(DynamoDBOperations operations, DynamodbHistoryLogService dynamodbHistoryLogService, ObjectMapper objectMapper) {
        super(operations, WorldEventScheduleDoc.class, dynamodbHistoryLogService, objectMapper);
    }

    private boolean isEvent(Integer sk){
        Key key = Key.builder()
                .partitionValue(DynamoDBConstants.PK_KEY_WORLD_EVENT_SCHEDULER)
                .sortValue(String.valueOf(sk))
                .build();

        WorldEventScheduleDoc doc = findById(key);

        return doc != null;
    }

    @Override
    public void insert(WorldEventRequest worldEventRequest) {
        if(isEvent(worldEventRequest.getId().intValue())){
            log.error("insert EventId: {} is duplication", worldEventRequest.getId());
            throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage());
        }

        LocalDateTime nowDate = LocalDateTime.now();

        try {
            WorldEventScheduleAttrib attrib = new WorldEventScheduleAttrib();
            attrib.setAttribType(DynamoDBConstants.ATTRIB_WORLD_EVENT_SCHEDULER);
            attrib.setActive(true);
            attrib.setId(worldEventRequest.getId().intValue());
            attrib.setStartTime(convertUTCDate(worldEventRequest.getStartDt()));
            attrib.setEndTime(convertUTCDate(worldEventRequest.getEndDt()));
            attrib.setGlobalEventContributionPointMax(worldEventRequest.getMaxPoint());
            attrib.setGlobalEventActionGroupId(worldEventRequest.getGlobalEventActionId());
            attrib.setPersonalEventActionGroupId(worldEventRequest.getPersonalEventActionId());

            WorldEventScheduleDoc doc = new WorldEventScheduleDoc();
            doc.setPK(DynamoDBConstants.PK_KEY_WORLD_EVENT_SCHEDULER);
            doc.setSK(String.valueOf(worldEventRequest.getId()));
            doc.setDocType(DynamoDBConstants.DOC_WORLD_EVENT_SCHEDULER);
            doc.setAttribValue(objectMapper.writeValueAsString(attrib));
            doc.setCreatedDateTime(convertUTCDate(nowDate));
            doc.setUpdatedDateTime(convertUTCDate(nowDate));
            doc.setDeletedDateTime(DynamoDBConstants.MIN_DATE);
            doc.setRestoredDateTime(DynamoDBConstants.MIN_DATE);

            save(doc);

        }catch (Exception e){
            log.error("insert Error: {}", e.getMessage());
            throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage());
        }
    }

    @Override
    public void update(WorldEventRequest worldEventRequest) {
        LocalDateTime nowDate = LocalDateTime.now();

        try {
            Key key = Key.builder()
                    .partitionValue(DynamoDBConstants.PK_KEY_WORLD_EVENT_SCHEDULER)
                    .sortValue(String.valueOf(worldEventRequest.getId()))
                    .build();

            WorldEventScheduleDoc beforeDoc = findById(key);

            if (beforeDoc != null) {
                WorldEventScheduleDoc afterDoc = deepCopy(beforeDoc, WorldEventScheduleDoc.class);

                WorldEventScheduleAttrib attrib = objectMapper.readValue(afterDoc.getAttribValue(), WorldEventScheduleAttrib.class);
                attrib.setActive(true);
                attrib.setStartTime(convertUTCDate(worldEventRequest.getStartDt()));
                attrib.setEndTime(convertUTCDate(worldEventRequest.getEndDt()));
                attrib.setGlobalEventContributionPointMax(worldEventRequest.getMaxPoint());
                attrib.setGlobalEventActionGroupId(worldEventRequest.getGlobalEventActionId());
                attrib.setPersonalEventActionGroupId(worldEventRequest.getPersonalEventActionId());

                afterDoc.setAttribValue(objectMapper.writeValueAsString(attrib));
                afterDoc.setUpdatedDateTime(CommonUtils.convertUTCDate(nowDate));

                update(afterDoc);

                log.info("WorldEventScheduleDoc Update Success: {}", objectMapper.writeValueAsString(afterDoc));

            }
        }catch (Exception e){
            throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage());
        }
    }

    @Override
    public DynamodbOperationResult delete(String id) {
        try{
            Key key = Key.builder()
                    .partitionValue(DynamoDBConstants.PK_KEY_BATTLE_EVENT)
                    .sortValue(id)
                    .build();
            WorldEventScheduleDoc doc = findById(key);

            if(doc != null) {
                Key detailKey = Key.builder()
                        .partitionValue(doc.getPK())
                        .sortValue(doc.getSK())
                        .build();

                delete(detailKey);

                log.info("WorldEventScheduleDoc Delete Success: {}", objectMapper.writeValueAsString(doc));

                return new DynamodbOperationResult(true, "", doc);
            }
            return new DynamodbOperationResult(true, "null", null);
        }catch (Exception e){
            log.error("delete WorldEventScheduleDoc Error: {}", e.getMessage());
            return new DynamodbOperationResult(false, e.getMessage(), null);
        }
    }
}
