package com.cameleer.server.app.controller;

import com.cameleer.server.app.dto.AgentEventPageResponse;
import com.cameleer.server.app.dto.AgentEventResponse;
import com.cameleer.server.app.web.EnvPath;
import com.cameleer.server.core.agent.AgentEventPage;
import com.cameleer.server.core.agent.AgentEventService;
import com.cameleer.server.core.runtime.Environment;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
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;

@RestController
@RequestMapping("/api/v1/environments/{envSlug}/agents/events")
@Tag(name = "Agent Events", description = "Agent lifecycle event log (env-scoped)")
public class AgentEventsController {

    private final AgentEventService agentEventService;

    public AgentEventsController(AgentEventService agentEventService) {
        this.agentEventService = agentEventService;
    }

    @GetMapping
    @Operation(summary = "Query agent events in this environment",
            description = "Cursor-paginated. Returns newest first. Pass nextCursor back as ?cursor= for the next page.")
    @ApiResponse(responseCode = "200", description = "Event page returned")
    public ResponseEntity<AgentEventPageResponse> getEvents(
            @EnvPath Environment env,
            @RequestParam(required = false) String appId,
            @RequestParam(required = false) String agentId,
            @RequestParam(required = false) String from,
            @RequestParam(required = false) String to,
            @RequestParam(required = false) String cursor,
            @RequestParam(defaultValue = "50") int limit) {

        Instant fromInstant = from != null ? Instant.parse(from) : null;
        Instant toInstant = to != null ? Instant.parse(to) : null;

        AgentEventPage page = agentEventService.queryEventPage(
                appId, agentId, env.slug(), fromInstant, toInstant, cursor, limit);

        var data = page.data().stream().map(AgentEventResponse::from).toList();

        return ResponseEntity.ok(new AgentEventPageResponse(data, page.nextCursor(), page.hasMore()));
    }
}
