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

import com.caliverse.admin.domain.entity.HISTORYTYPE;
import com.caliverse.admin.domain.request.LandRequest;
import com.caliverse.admin.dynamodb.domain.atrrib.LandAttrib;
import com.caliverse.admin.dynamodb.domain.doc.LandDoc;
import com.caliverse.admin.dynamodb.entity.DynamodbOperationResult;
import com.caliverse.admin.dynamodb.repository.BaseDynamoDBRepository;
import com.caliverse.admin.dynamodb.repository.LandRepository;
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.core.JsonProcessingException;
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 LandRepositoryImpl extends BaseDynamoDBRepository<LandDoc> implements LandRepository {
    public LandRepositoryImpl(DynamoDBOperations operations, DynamodbHistoryLogService dynamodbHistoryLogService, ObjectMapper objectMapper) {
        super(operations, LandDoc.class, dynamodbHistoryLogService, objectMapper);
    }

    @Override
    public LandAttrib findLandAttrib(Integer landId) {
        Key key = Key.builder()
                .partitionValue(DynamoDBConstants.PK_KEY_LAND + landId)
                .sortValue(DynamoDBConstants.EMPTY)
                .build();

        LandDoc doc = findById(key);
        if (doc == null) return null;
        String attribJson = doc.getAttribValue();
        try {
            return objectMapper.readValue(attribJson, LandAttrib.class);
        } catch (JsonProcessingException e) {
            throw new RestApiException(CommonCode.ERROR.getHttpStatus(),
                    ErrorCode.DYNAMODB_JSON_PARSE_ERROR.getMessage());
        }
    }

    @Override
    public void insertLand(LandRequest landRequest) {
        try {
            LocalDateTime nowDate = LocalDateTime.now();

            int land_id = landRequest.getLandId();
            String guid = landRequest.getUserGuid();

            String pk = DynamoDBConstants.PK_KEY_LAND + land_id;

            LandAttrib attrib = new LandAttrib();
            attrib.setAttribType(DynamoDBConstants.ATTRIB_LAND);
            attrib.setLandName("");
            attrib.setLandMetaId(land_id);
            attrib.setDescription("");
            attrib.setOwnerUserGuid(guid);

            LandDoc doc = new LandDoc();
            doc.setPK(pk);
            doc.setSK(DynamoDBConstants.EMPTY);
            doc.setDocType(DynamoDBConstants.DOC_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("LandDoc Insert Success: {}", objectMapper.writeValueAsString(doc));

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

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

    @Override
    public void updateLand(LandRequest landRequest) {
        LocalDateTime nowDate = LocalDateTime.now();

        int land_id = landRequest.getLandId();
        String guid = landRequest.getUserGuid();

        try {
            Key key = Key.builder()
                    .partitionValue(DynamoDBConstants.PK_KEY_LAND + land_id)
                    .sortValue(DynamoDBConstants.EMPTY)
                    .build();

            LandDoc beforeDoc = findById(key);

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

                LandAttrib attrib = objectMapper.readValue(afterDoc.getAttribValue(), LandAttrib.class);
                attrib.setDescription("");
                attrib.setOwnerUserGuid(guid);

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

                update(afterDoc);

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

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

    @Override
    public DynamodbOperationResult initLandOwner(int landId) {
        LocalDateTime nowDate = LocalDateTime.now();

        try {
            Key key = Key.builder()
                    .partitionValue(DynamoDBConstants.PK_KEY_LAND + landId)
                    .sortValue(DynamoDBConstants.EMPTY)
                    .build();

            LandDoc beforeDoc = findById(key);

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

                LandAttrib attrib = objectMapper.readValue(afterDoc.getAttribValue(), LandAttrib.class);
                attrib.setOwnerUserGuid("");

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

                update(afterDoc);

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

                dynamodbHistoryLogService.updateHistoryLog(
                        HISTORYTYPE.LAND_OWNED_INITIALIZE,
                        HISTORYTYPE.LAND_OWNED_INITIALIZE.name(),
                        beforeDoc,
                        afterDoc
                );

                return new DynamodbOperationResult(true, "",afterDoc);
            }
            return new DynamodbOperationResult(false, "null",null);
        }catch (Exception e){
            log.error("Init Land Owner Error: {}", e.getMessage());
            return new DynamodbOperationResult(false, e.getMessage(),null);
        }
    }

    @Override
    public DynamodbOperationResult initLandDesc(int landId) {
        LocalDateTime nowDate = LocalDateTime.now();
        try {
            Key key = Key.builder()
                    .partitionValue(DynamoDBConstants.PK_KEY_LAND + landId)
                    .sortValue(DynamoDBConstants.EMPTY)
                    .build();

            LandDoc beforeDoc = findById(key);

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

                LandAttrib attrib = objectMapper.readValue(afterDoc.getAttribValue(), LandAttrib.class);
                attrib.setDescription("");
                attrib.setLandName("");

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

                update(afterDoc);

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

                dynamodbHistoryLogService.updateHistoryLog(
                        HISTORYTYPE.LAND_DESC_INITIALIZE,
                        HISTORYTYPE.LAND_DESC_INITIALIZE.name(),
                        beforeDoc,
                        afterDoc
                );
                return new DynamodbOperationResult(true, "Success",afterDoc);
            }
            return new DynamodbOperationResult(false, "null",beforeDoc);
        }catch (Exception e){
            log.error("Init Land Desc Error: {}", e.getMessage());
            return new DynamodbOperationResult(false, e.getMessage(),null);
        }
    }
}
