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

import com.caliverse.admin.dynamodb.domain.atrrib.NicknameAttrib;
import com.caliverse.admin.dynamodb.domain.doc.NicknameDoc;
import com.caliverse.admin.dynamodb.repository.BaseDynamoDBRepository;
import com.caliverse.admin.dynamodb.repository.NicknameRepository;
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.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;

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

    @Override
    public NicknameAttrib findUser(String guid) {
        Key key = Key.builder()
                .partitionValue(DynamoDBConstants.PK_KEY_NICKNAME + guid)
                .sortValue(DynamoDBConstants.EMPTY)
                .build();

        NicknameDoc doc = findById(key);

        if (doc == null) return null;

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