package com.cameleer.server.app.controller;

import com.cameleer.server.app.storage.ClickHouseUsageTracker;
import com.cameleer.server.core.analytics.UsageStats;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;

@RestController
@RequestMapping("/api/v1/admin/usage")
@ConditionalOnBean(ClickHouseUsageTracker.class)
@Tag(name = "Usage Analytics", description = "UI usage pattern analytics")
public class UsageAnalyticsController {

    private final ClickHouseUsageTracker tracker;

    public UsageAnalyticsController(ClickHouseUsageTracker tracker) {
        this.tracker = tracker;
    }

    @GetMapping
    @Operation(summary = "Query usage statistics",
            description = "Returns aggregated API usage stats grouped by endpoint, user, or hour")
    public ResponseEntity<List<UsageStats>> getUsage(
            @RequestParam(required = false) String from,
            @RequestParam(required = false) String to,
            @RequestParam(required = false) String username,
            @RequestParam(defaultValue = "endpoint") String groupBy) {

        Instant fromInstant = from != null ? Instant.parse(from) : Instant.now().minus(7, ChronoUnit.DAYS);
        Instant toInstant = to != null ? Instant.parse(to) : Instant.now();

        List<UsageStats> stats = switch (groupBy) {
            case "user" -> tracker.queryByUser(fromInstant, toInstant);
            case "hour" -> tracker.queryByHour(fromInstant, toInstant, username);
            default -> tracker.queryByEndpoint(fromInstant, toInstant, username);
        };

        return ResponseEntity.ok(stats);
    }
}
