package com.saas.tenant.controller;

import com.saas.shared.core.TenantContext;
import com.saas.tenant.entity.InboundCallRequest;
import com.saas.tenant.entity.InboundCallData;
import com.saas.tenant.service.InboundCallService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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.time.LocalDateTime;
import java.util.List;

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

    private final InboundCallService inboundCallService;

    @GetMapping("/inbound")
    public ResponseEntity<Page<InboundCallData>> getInboundCalls(
            
            Pageable pageable) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("📞 Tenant {} requesting inbound calls (page: {}, size: {})", 
                tenantId, pageable.getPageNumber(), pageable.getPageSize());
        
        Page<InboundCallData> inboundCalls = inboundCallService.getAllInboundCallsPaginated(pageable);
        return ResponseEntity.ok(inboundCalls);
    }

    @GetMapping("/inbound/{callSid}")
    public ResponseEntity<InboundCallData> getInboundCallByCallSid(
            
            @PathVariable String callSid) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("🔍 Tenant {} requesting inbound call: {}", tenantId, callSid);
        
        return inboundCallService.getInboundCallByCallSid(callSid)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/records")
    public ResponseEntity<List<InboundCallRequest>> getCallRecords(
            
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate,
            @RequestParam(required = false) String provider) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("📋 Tenant {} requesting call records - provider: {}, start: {}, end: {}", 
                tenantId, provider, startDate, endDate);
        
        List<InboundCallRequest> callRecords;
        
        if (provider != null) {
            callRecords = inboundCallService.getCallRecordsByProvider(provider);
        } else if (startDate != null && endDate != null) {
            callRecords = inboundCallService.getCallRecordsByDateRange(startDate, endDate);
        } else {
            callRecords = inboundCallService.getAllCallRecords();
        }
        
        return ResponseEntity.ok(callRecords);
    }

    @GetMapping("/records/{callSid}")
    public ResponseEntity<InboundCallRequest> getCallRecordByCallSid(
            
            @PathVariable String callSid) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("🔍 Tenant {} requesting call record: {}", tenantId, callSid);
        
        return inboundCallService.getCallRecordByCallSid(callSid)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/patient/{phoneNumber}")
    public ResponseEntity<List<InboundCallRequest>> getCallRecordsByPatientPhone(
            
            @PathVariable String phoneNumber) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("📞 Tenant {} requesting calls for patient: {}", tenantId, phoneNumber);
        
        List<InboundCallRequest> callRecords = inboundCallService.getCallRecordsByPatientPhone(phoneNumber);
        return ResponseEntity.ok(callRecords);
    }

    @GetMapping("/recent")
    public ResponseEntity<List<InboundCallRequest>> getRecentCalls(
            
            @RequestParam(defaultValue = "10") int limit) {
        
        String tenantId = TenantContext.getTenantId();
        log.info("📋 Tenant {} requesting {} most recent calls", tenantId, limit);
        
        List<InboundCallRequest> recentCalls = inboundCallService.getRecentCallRecords(limit);
        return ResponseEntity.ok(recentCalls);
    }

    @GetMapping("/statistics")
    public ResponseEntity<java.util.Map<String, Object>> getCallStatistics(
            
            @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 call statistics", tenantId);
        
        List<InboundCallRequest> records;
        if (startDate != null && endDate != null) {
            records = inboundCallService.getCallRecordsByDateRange(startDate, endDate);
        } else {
            records = inboundCallService.getAllCallRecords();
        }
        
        long totalCalls = records.size();
        long callsWithAppointments = records.stream()
                .filter(cr -> cr.getAppointmentDateTime() != null)
                .count();
        long totalDuration = records.stream()
                .filter(cr -> cr.getDuration() != null && cr.getDuration() > 0)
                .mapToLong(InboundCallRequest::getDuration)
                .sum();
        
        java.util.Map<String, Object> stats = java.util.Map.of(
                "totalCalls", totalCalls,
                "callsWithAppointments", callsWithAppointments,
                "totalDurationSeconds", totalDuration,
                "averageDurationSeconds", totalCalls > 0 ? totalDuration / totalCalls : 0
        );
        
        return ResponseEntity.ok(stats);
    }
}
