package com.saas.tenant.service;

import com.saas.tenant.entity.AiApiCostRecord;
import com.saas.tenant.repository.AiApiCostRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Tenant AI API Cost Service
 * 
 * Manages AI provider costs (OpenAI, ElevenLabs, Gemini) in tenant-specific database
 * - Uses NEW tenant/entity/AiApiCostRecord (NO tenantId)
 * - Physical isolation via database-per-tenant
 * - Separate from VoIP costs (CallCostRecord) - Single Responsibility Principle
 * 
 * Architecture:
 * - AI costs: OPENAI, ELEVENLABS, GEMINI, ANTHROPIC
 * - Cost types: REALTIME_API, TTS, STT, LLM, COMPLETION
 * - Linked to calls via callSid
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TenantAiApiCostService {
    
    private final AiApiCostRecordRepository aiApiCostRecordRepository;
    
    @Transactional(transactionManager = "tenantTransactionManager")
    public AiApiCostRecord saveAiApiCost(AiApiCostRecord costRecord) {
        log.info("🤖 Saving AI API cost record - CallSid: {}, Provider: {}, Type: {}, Cost: {} {}", 
                costRecord.getCallSid(), costRecord.getAiProvider(), costRecord.getCostType(), 
                costRecord.getCost(), costRecord.getCurrency());
        
        return aiApiCostRecordRepository.save(costRecord);
    }
    
    @Transactional(transactionManager = "tenantTransactionManager", readOnly = true)
    public List<AiApiCostRecord> getAiCostsByCallSid(String callSid) {
        return aiApiCostRecordRepository.findByCallSid(callSid);
    }
    
    @Transactional(transactionManager = "tenantTransactionManager", readOnly = true)
    public List<AiApiCostRecord> getAiCostsByProvider(String aiProvider) {
        return aiApiCostRecordRepository.findByAiProvider(aiProvider);
    }
    
    @Transactional(transactionManager = "tenantTransactionManager", readOnly = true)
    public Map<String, Object> getAiCostReport(LocalDateTime startDate, LocalDateTime endDate) {
        Map<String, Object> report = new HashMap<>();
        
        BigDecimal totalCost = aiApiCostRecordRepository.getTotalCostBetween(startDate, endDate);
        List<Object[]> costByProvider = aiApiCostRecordRepository.getCostByProviderBetween(startDate, endDate);
        List<Object[]> costByType = aiApiCostRecordRepository.getCostByTypeBetween(startDate, endDate);
        
        report.put("totalCost", totalCost != null ? totalCost : BigDecimal.ZERO);
        report.put("startDate", startDate);
        report.put("endDate", endDate);
        
        Map<String, BigDecimal> providerCosts = new HashMap<>();
        for (Object[] row : costByProvider) {
            String provider = (String) row[0];
            BigDecimal cost = (BigDecimal) row[1];
            providerCosts.put(provider, cost);
        }
        report.put("costByProvider", providerCosts);
        
        Map<String, BigDecimal> typeCosts = new HashMap<>();
        for (Object[] row : costByType) {
            String type = (String) row[0];
            BigDecimal cost = (BigDecimal) row[1];
            typeCosts.put(type, cost);
        }
        report.put("costByType", typeCosts);
        
        log.info("📊 AI cost report generated - Total: {} USD, Period: {} to {}", 
                totalCost, startDate, endDate);
        
        return report;
    }
    
    @Transactional(transactionManager = "tenantTransactionManager", readOnly = true)
    public List<AiApiCostRecord> getAllAiCosts(LocalDateTime startDate, LocalDateTime endDate) {
        return aiApiCostRecordRepository.findByCallStartTimeBetween(startDate, endDate);
    }
}
