package com.saas.tenant.controller;

import com.saas.shared.core.TenantContext;
import com.saas.tenant.entity.CallCostRecord;
import com.saas.tenant.service.CallCostTrackingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/tenant/costs")
@PreAuthorize("hasRole('TENANT_USER')")
@RequiredArgsConstructor
@Slf4j
public class TenantCostController {

    private final CallCostTrackingService callCostTrackingService;

    @GetMapping("/summary")
    public ResponseEntity<Map<String, Object>> getCostSummary(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("📊 Tenant {} requesting cost summary - start: {}, end: {}", tenantId, startDate, endDate);
        
        Map<String, Object> summary = callCostTrackingService.getTenantCostSummary(
                tenantId, startDate, endDate);
        
        return ResponseEntity.ok(summary);
    }

    @GetMapping
    public ResponseEntity<List<CallCostRecord>> getAllCosts(
            @RequestParam(required = false) String provider,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("📋 Tenant {} requesting all costs - provider: {}, start: {}, end: {}", 
                tenantId, provider, startDate, endDate);
        
        List<CallCostRecord> costs;
        
        if (provider != null) {
            costs = callCostTrackingService.getCostsByProvider(provider);
        } else if (startDate != null && endDate != null) {
            costs = callCostTrackingService.getCostsByDateRange(startDate, endDate);
        } else {
            costs = callCostTrackingService.getAllCosts();
        }
        
        return ResponseEntity.ok(costs);
    }

    @GetMapping("/call/{callSid}")
    public ResponseEntity<CallCostRecord> getCostByCallSid(
            @PathVariable String callSid) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("🔍 Tenant {} requesting cost for call: {}", tenantId, callSid);
        
        return callCostTrackingService.getCallCostByCallSid(callSid)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/total")
    public ResponseEntity<BigDecimal> getTotalCost(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("💰 Tenant {} requesting total cost - start: {}, end: {}", tenantId, startDate, endDate);
        
        BigDecimal total;
        if (startDate != null && endDate != null) {
            List<CallCostRecord> costs = callCostTrackingService.getCostsByDateRange(startDate, endDate);
            total = costs.stream()
                    .map(CallCostRecord::getCost)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        } else {
            total = callCostTrackingService.getAllCosts().stream()
                    .map(CallCostRecord::getCost)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        
        return ResponseEntity.ok(total);
    }

    @GetMapping("/by-provider")
    public ResponseEntity<Map<String, BigDecimal>> getCostsByProvider() {
        
        String tenantId = TenantContext.getTenantId();
        log.info("📊 Tenant {} requesting costs grouped by provider", tenantId);
        
        List<CallCostRecord> allCosts = callCostTrackingService.getAllCosts();
        
        Map<String, BigDecimal> costsByProvider = allCosts.stream()
                .collect(java.util.stream.Collectors.groupingBy(
                        CallCostRecord::getProvider,
                        java.util.stream.Collectors.reducing(
                                BigDecimal.ZERO,
                                CallCostRecord::getCost,
                                BigDecimal::add
                        )
                ));
        
        return ResponseEntity.ok(costsByProvider);
    }
}
