package com.saas.admin.service;

import com.saas.admin.entity.PhoneNumber;
import com.saas.admin.repository.PhoneNumberRepository;
import com.saas.shared.enums.Provider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Slf4j
@RequiredArgsConstructor
@Transactional
public class PhoneNumberService {

    private final PhoneNumberRepository phoneNumberRepository;

    public PhoneNumber createPhoneNumber(PhoneNumber phoneNumber) {
        log.info("📞 Creating {} phone number: {} for tenant ID: {}", 
                phoneNumber.getProvider(), phoneNumber.getPhoneNumber(), phoneNumber.getTenantId());
        return phoneNumberRepository.save(phoneNumber);
    }

    public Optional<String> getTenantIdByPhoneNumber(String phoneNumber) {
        log.debug("🔍 Looking up tenant for phone number: {}", phoneNumber);
        return phoneNumberRepository.findByPhoneNumberAndIsActive(phoneNumber, true)
                .map(PhoneNumber::getTenantId);
    }

    public Optional<String> getTenantIdByPhoneNumber(String phoneNumber, Provider provider) {
        log.debug("🔍 Looking up tenant for {} phone number: {}", provider, phoneNumber);
        return phoneNumberRepository.findByPhoneNumberAndProvider(phoneNumber, provider)
                .filter(PhoneNumber::getIsActive)
                .map(PhoneNumber::getTenantId);
    }

    public List<PhoneNumber> getPhoneNumbersByTenant(String tenantId) {
        log.debug("📋 Fetching phone numbers for tenant ID: {}", tenantId);
        return phoneNumberRepository.findByTenantId(tenantId);
    }

    public List<PhoneNumber> getPhoneNumbersByTenant(String tenantId, Provider provider) {
        log.debug("📋 Fetching {} phone numbers for tenant ID: {}", provider, tenantId);
        return phoneNumberRepository.findByTenantIdAndProvider(tenantId, provider);
    }

    public List<PhoneNumber> getAllActivePhoneNumbers() {
        log.debug("📋 Fetching all active phone numbers");
        return phoneNumberRepository.findByIsActive(true);
    }

    public List<PhoneNumber> getPhoneNumbersByActiveStatus(Boolean isActive) {
        log.debug("📋 Fetching phone numbers with isActive={}", isActive);
        return phoneNumberRepository.findByIsActive(isActive);
    }

    public List<PhoneNumber> getAllPhoneNumbersByProvider(Provider provider) {
        log.debug("📋 Fetching all {} phone numbers", provider);
        return phoneNumberRepository.findByProvider(provider);
    }

    public PhoneNumber updatePhoneNumber(Long id, PhoneNumber updates) {
        return phoneNumberRepository.findById(id)
                .map(existing -> {
                    if (updates.getFriendlyName() != null) {
                        existing.setFriendlyName(updates.getFriendlyName());
                    }
                    if (updates.getDescription() != null) {
                        existing.setDescription(updates.getDescription());
                    }
                    if (updates.getIsActive() != null) {
                        existing.setIsActive(updates.getIsActive());
                    }
                    log.info("✏️ Updated phone number ID: {}", id);
                    return phoneNumberRepository.save(existing);
                })
                .orElseThrow(() -> new RuntimeException("Phone number not found: " + id));
    }

    public void deletePhoneNumber(Long id) {
        log.info("🗑️ Deleting phone number ID: {}", id);
        phoneNumberRepository.deleteById(id);
    }

    public void deactivatePhoneNumber(Long id) {
        phoneNumberRepository.findById(id).ifPresent(phoneNumber -> {
            phoneNumber.setIsActive(false);
            phoneNumberRepository.save(phoneNumber);
            log.info("⛔ Deactivated phone number ID: {}", id);
        });
    }

    public Optional<PhoneNumber> getPhoneNumberByNumber(String phoneNumber) {
        return phoneNumberRepository.findByPhoneNumber(phoneNumber);
    }

    public Optional<PhoneNumber> getPhoneNumberById(Long id) {
        log.debug("🔍 Fetching phone number by ID: {}", id);
        return phoneNumberRepository.findById(id);
    }

    public List<PhoneNumber> getAllPhoneNumbers() {
        log.debug("📋 Fetching all phone numbers");
        return phoneNumberRepository.findAll();
    }

    public void activatePhoneNumber(Long id) {
        phoneNumberRepository.findById(id).ifPresent(phoneNumber -> {
            phoneNumber.setIsActive(true);
            phoneNumberRepository.save(phoneNumber);
            log.info("✅ Activated phone number ID: {}", id);
        });
    }
}
