package com.ikon.projectmanagement.service.etl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.stereotype.Component;

import com.ikon.connector.dto.response.FieldsConfigDto;
import com.ikon.connector.spi.ConnectorDataSync;
import com.ikon.projectmanagement.entity.Role;
import com.ikon.projectmanagement.repository.RoleRepository;

import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;

/**
 * RoleConnector: Maps external role data to local Role entity.
 * 
 * This connector syncs role information from an external system.
 * It handles field mapping, type conversion, and persistence of Role records.
 */
@Component
@RequiredArgsConstructor
public class RoleConnector implements ConnectorDataSync {

    private final RoleRepository roleRepository;

    /**
     * Define the configuration for fields that will be synced from the external
     * source.
     * This specifies the external field names, labels, and their data types.
     */
    @Override
    public List<FieldsConfigDto> getFieldsConfig() {
        List<FieldsConfigDto> fieldsConfig = new ArrayList<>();

        fieldsConfig.add(FieldsConfigDto.builder()
                .key("id")
                .label("Role ID")
                .type("string")
                .build());

        fieldsConfig.add(FieldsConfigDto.builder()
                .key("accountId")
                .label("Account ID")
                .type("string")
                .build());

        fieldsConfig.add(FieldsConfigDto.builder()
                .key("role")
                .label("Role")
                .type("string")
                .build());

        return fieldsConfig;
    }

    /**
     * Returns the module name for this connector.
     * Used for identification and logging purposes.
     */
    @Override
    public String getModule() {
        return "Role";
    }

    /**
     * Core method that processes incoming role data from an external source.
     * 
     * Process flow:
     * 1. Extract and parse fields from Map
     * 2. Convert data types using utility methods
     * 3. Build Role entity
     * 4. Save to repository
     * 
     * @param payload List of Map objects containing role data from external source
     */
    @Override
    @Transactional
    public void syncBatch(List<Map<String, Object>> payload) {
        payload.stream()
                .forEach(data -> {
                    Role role = Role.builder()
                            .id(data.get("id") != null ? UUID.fromString(data.get("id").toString()) : null)
                            .accountId(data.get("id") != null ? UUID.fromString(data.get("id").toString()) : null)
                            .role(data.get("role") != null ? data.get("role").toString() : null)
                            .build();
                    roleRepository.save(role);
                });
    }

}
