package kr.co.accura.wtm.api;

import kr.co.accura.wbx.spring.common.SecurityUtils;
import kr.co.accura.wtm.domain.approval.repository.TtApprovalLineRepository;
import kr.co.accura.wtm.domain.timesheet.TimesheetStatus;
import kr.co.accura.wtm.domain.timesheet.repository.TimesheetRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/wtm/home")
@RequiredArgsConstructor
public class HomeController {

    private final TimesheetRepository timesheetRepository;
    private final TtApprovalLineRepository approvalLineRepository;

    @GetMapping("/dashboard")
    public Map<String, Object> dashboard() {
        Long userId = SecurityUtils.getCurrentUserId();
        Map<String, Object> data = new HashMap<>();

        // Current week timesheet status
        var recentTimesheets = timesheetRepository.findByUserId(userId, PageRequest.of(0, 5));
        data.put("recentTimesheets", recentTimesheets.getContent().stream().map(ts ->
                Map.of(
                        "id", ts.getId(),
                        "weekStartDate", ts.getWeekStartDate().toString(),
                        "status", ts.getStatus().name(),
                        "totalHours", ts.getTotalHours()
                )).toList());

        // Pending approvals count
        var pendingApprovals = approvalLineRepository.findPendingByApproverId(
                userId, PageRequest.of(0, 1));
        data.put("pendingApprovalCount", pendingApprovals.getTotalElements());

        return data;
    }

    @GetMapping("/notifications")
    public Map<String, Object> notifications() {
        Long userId = SecurityUtils.getCurrentUserId();
        Map<String, Object> data = new HashMap<>();

        // Pending approval notifications
        var pendingLines = approvalLineRepository.findPendingByApproverId(
                userId, PageRequest.of(0, 10));
        data.put("items", pendingLines.getContent().stream().map(line ->
                Map.of(
                        "type", "APPROVAL_REQUEST",
                        "title", "시수 결재 요청",
                        "message", "결재 대기 항목이 있습니다. (결재라인 #" + line.getId() + ")",
                        "createdAt", line.getCreatedAt() != null ? line.getCreatedAt().toString() : ""
                )).toList());
        data.put("total", pendingLines.getTotalElements());

        return data;
    }
}
