package com.unicorn.hgzero.ai.infra.controller;

import com.unicorn.hgzero.ai.biz.domain.ExtractedTodo;
import com.unicorn.hgzero.ai.biz.usecase.TodoExtractionUseCase;
import com.unicorn.hgzero.ai.infra.dto.request.TodoExtractionRequest;
import com.unicorn.hgzero.ai.infra.dto.response.TodoExtractionResponse;
import com.unicorn.hgzero.ai.infra.dto.common.ExtractedTodoDto;
import com.unicorn.hgzero.common.dto.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Todo 자동 추출 Controller
 * POST /api/todos/extract
 */
@RestController
@RequestMapping("/api/ai/todos")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "Todo", description = "Todo 자동 추출 API")
public class TodoController {

    private final TodoExtractionUseCase todoExtractionUseCase;

    @PostMapping("/extract")
    @Operation(summary = "Todo 자동 추출", description = "회의록에서 액션 아이템을 자동으로 추출하고 담당자를 식별합니다")
    public ResponseEntity<ApiResponse<TodoExtractionResponse>> extractTodos(
            @RequestHeader("X-User-Id") String userId,
            @Valid @RequestBody TodoExtractionRequest request) {

        log.info("Todo 추출 요청 - meetingId: {}, userId: {}", request.getMeetingId(), userId);

        List<ExtractedTodo> todos = todoExtractionUseCase.extractTodos(
            request.getMeetingId(),
            request.getMinutesContent(),
            request.getUserId() != null ? request.getUserId() : userId
        );

        TodoExtractionResponse response = TodoExtractionResponse.builder()
                .meetingId(request.getMeetingId())
                .todos(todos.stream()
                        .map(t -> ExtractedTodoDto.builder()
                                .content(t.getContent())
                                .assignee(t.getAssignee())
                                .dueDate(t.getDueDate())
                                .priority(t.getPriority())
                                .sectionReference(t.getSectionReference())
                                .build())
                        .collect(Collectors.toList()))
                .totalCount(todos.size())
                .extractedAt(LocalDateTime.now())
                .build();

        return ResponseEntity.ok(ApiResponse.success(response));
    }
}
