package com.bytesw.bytebot.etl.services;

import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensRegistryBean;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.service.provider.TwilioService;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class DeleteSensMessageService {

    @Autowired
    private TwilioService twilioService;

    @Autowired
    DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;

    public List<DeleteDataSensRegistryBean> deleteMessage(Long agentId, String SmsMessage, Long inten_id, String sender_id) throws Exception {
        List<DeleteDataSensRegistryBean> deleteMessages = new ArrayList<DeleteDataSensRegistryBean>();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("agent_id", agentId.intValue());
        try {
            Map<String, Object> result = new HashMap<>();
            data = twilioService.generateInfo(SmsMessage, params);

            if (data.isEmpty()) {
                throw new Exception("Parámetros vacíos");
            }

            DeleteDataSensRegistryBean registry = new DeleteDataSensRegistryBean();

            if (data.get("status") != null) {
                List<String> images = new ArrayList<String>();
                images = (List<String>) data.get("data");
                for (String image : images) {
                    if (image.trim().isEmpty()) {
                        continue;
                    }
                    // Info del Bean
                    registry.setMultimedia_sid(image);
                    registry.setMessage_sid(SmsMessage);
                    registry.setUpdate_time(OffsetDateTime.now());
                    registry.setInten_id(inten_id);
                    registry.setSender_id(sender_id);
                    // Agregado a la lista
                    deleteMessages.add(registry);
                }
            }
            return deleteMessages;
        } catch (NotFoundException e) {
            log.debug(e);
            throw new NotFoundException(e.getMessage());
        } catch (Exception e) {
            log.debug(e);
            throw new Exception(e.getMessage());
        }
    }
}
