package com.caliverse.admin.dynamodb.repository;

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.exception.RestApiException;
import com.caliverse.admin.history.service.DynamodbHistoryLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;

import java.util.List;

@RequiredArgsConstructor
public abstract class BaseDynamoDBRepository<T> implements DynamoDBRepository<T> {
    protected final DynamoDBOperations operations;
    protected final Class<T> entityClass;
    protected final DynamodbHistoryLogService dynamodbHistoryLogService;
    protected final ObjectMapper objectMapper;

    @Override
    public void save(T item) {
        operations.addPutItem(item, entityClass);
    }

    @Override
    public void saveWithCondition(T item, Expression condition) {
        operations.addConditionPutItem(item, entityClass, condition);
    }

    @Override
    public void update(T item) {
        operations.addUpdateItem(item, entityClass);
    }

    @Override
    public void updateWithCondition(T item, Expression condition) {
        operations.addConditionUpdateItem(item, entityClass, condition);
    }

    @Override
    public void delete(Key key) {
        operations.addDeleteItem(key, entityClass);
    }

    @Override
    public void deleteWithCondition(Key key, Expression condition) {
        operations.addConditionDeleteItem(key, entityClass, condition);
    }

    @Override
    public T findById(Key key) {
        return operations.getItem(key, entityClass);
    }

    @Override
    public List<T> findAll(Key key) {
        return operations.getQueryItems(key, entityClass);
    }

    @Override
    public List<T> findAllScan(String prefix) {
        return operations.getItemsScanBegins(prefix, entityClass);
    }

    @Override
    public List<T> findAllScan(String prefix, String sortKey) {
        return operations.getItemsScanBegins(prefix, sortKey, entityClass);
    }

    protected <T> T deepCopy(T source, Class<T> valueType) {
        try {
            return objectMapper.readValue(objectMapper.writeValueAsString(source), valueType);
        } catch (JsonProcessingException e) {
            throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_JSON_PARSE_ERROR.getMessage());
        }
    }

    @Override
    public List<T> findByPrefix(String partitionKey, String sortKeyPrefix) {
        if(sortKeyPrefix.isEmpty()){
            return operations.getItemsByPrefix(partitionKey, entityClass);
        }
        else{
            return operations.getItemsByPrefix(partitionKey, sortKeyPrefix, entityClass);
        }
    }
}
