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

import com.caliverse.admin.domain.entity.HISTORYTYPE;
import com.caliverse.admin.dynamodb.domain.atrrib.OwnedLandAttrib;
import com.caliverse.admin.dynamodb.domain.doc.OwnedLandDoc;
import com.caliverse.admin.dynamodb.entity.EOwnedType;
import com.caliverse.admin.dynamodb.entity.DynamodbOperationResult;
import com.caliverse.admin.dynamodb.repository.BaseDynamoDBRepository;
import com.caliverse.admin.dynamodb.repository.OwnedLandRepository;
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.history.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 OwnedLandRepositoryImpl extends BaseDynamoDBRepository<OwnedLandDoc> implements OwnedLandRepository {
    public OwnedLandRepositoryImpl(DynamoDBOperations operations, DynamodbHistoryLogService dynamodbHistoryLogService, ObjectMapper objectMapper) {
        super(operations, OwnedLandDoc.class, dynamodbHistoryLogService, objectMapper);
    }

    @Override
    public OwnedLandDoc findOwnedLand(String guid, Integer landId) {
        Key key = Key.builder()
                .partitionValue(DynamoDBConstants.PK_KEY_OWNED_LAND + guid)
                .sortValue(String.valueOf(landId))
                .build();

        return findById(key);
    }

    @Override
    public void insert(String guid, Integer landId) {
        OwnedLandDoc ownedLand = findOwnedLand(guid, landId);
        if (ownedLand != null) {
            log.warn("OwnedLand guid: {}, landId: {} Exist", guid, landId);
            return;
        }

        try {
            LocalDateTime nowDate = LocalDateTime.now();

            String pk = DynamoDBConstants.PK_KEY_OWNED_LAND + guid;

            OwnedLandAttrib attrib = new OwnedLandAttrib();
            attrib.setAttribType(DynamoDBConstants.ATTRIB_OWNED_LAND);
            attrib.setLandMetaId(landId);
            attrib.setOwnedType(EOwnedType.Own.getValue());

            OwnedLandDoc doc = new OwnedLandDoc();
            doc.setPK(pk);
            doc.setSK(String.valueOf(landId));
            doc.setDocType(DynamoDBConstants.DOC_OWNED_LAND);
            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);

            log.info("OwnedLandDoc Insert Success: {}", objectMapper.writeValueAsString(doc));

            dynamodbHistoryLogService.insertHistoryLog(
                    HISTORYTYPE.LAND_OWNER_CHANGE_ADD,
                    HISTORYTYPE.LAND_OWNER_CHANGE_ADD.name(),
                    doc
            );

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

    @Override
    public void delete(String guid, Integer landId) {
        try {
            Key key = Key.builder()
                    .partitionValue(DynamoDBConstants.PK_KEY_OWNED_LAND + guid)
                    .sortValue(String.valueOf(landId))
                    .build();

            OwnedLandDoc doc = findById(key);

            delete(key);

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

            dynamodbHistoryLogService.deleteHistoryLog(
                    HISTORYTYPE.LAND_OWNER_CHANGE_UPDATE,
                    HISTORYTYPE.LAND_OWNER_CHANGE_UPDATE.name(),
                    doc
            );
        }catch (Exception e){
            log.error("delete Error: {}", e.getMessage());
            throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage());
        }
    }

    @Override
    public DynamodbOperationResult initOwnedLand(String guid, Integer landId) {
        try {
            Key key = Key.builder()
                    .partitionValue(DynamoDBConstants.PK_KEY_OWNED_LAND + guid)
                    .sortValue(String.valueOf(landId))
                    .build();

            OwnedLandDoc doc = findById(key);

            delete(key);

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

            dynamodbHistoryLogService.deleteHistoryLog(
                    HISTORYTYPE.LAND_OWNER_CHANGE_UPDATE,
                    HISTORYTYPE.LAND_OWNER_CHANGE_UPDATE.name(),
                    doc
            );
            return new DynamodbOperationResult(true, "", doc);
        }catch (Exception e){
            log.error("Init OwnedLand Error: {}", e.getMessage());
            return new DynamodbOperationResult(false, e.getMessage(), null);
        }
    }
}
