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

import com.caliverse.admin.dynamodb.domain.atrrib.CharacterBaseAttrib;
import com.caliverse.admin.dynamodb.domain.doc.CharacterBaseDoc;
import com.caliverse.admin.dynamodb.repository.BaseDynamoDBRepository;
import com.caliverse.admin.dynamodb.repository.CharacterBaseRepository;
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.mongodb.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.util.List;

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

    @Override
    public CharacterBaseAttrib findCharacter(String guid) {
        Key key = Key.builder()
                .partitionValue(DynamoDBConstants.PK_KEY_CHARACTER + guid)
                .build();

        List<CharacterBaseDoc> docList = findAll(key);
        CharacterBaseDoc doc = docList.get(0);

        try {
            return objectMapper.readValue(doc.getAttribValue(), CharacterBaseAttrib.class);
        } catch (JsonProcessingException e) {
            throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage());
        }
    }
}
