package com.writeoff.module.dashboard.controller;

import com.writeoff.common.api.ApiResponse;
import com.writeoff.security.AuthContext;
import com.writeoff.security.DataScopeType;
import com.writeoff.security.RequirePermission;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 租户工作台统计接口，聚合"活跃会议数"和"待财务确认账单数"等关键指标，
 * 为 TenantDashboardPage 提供实时数据。
 */
@RestController
@RequestMapping("/api/dashboard")
public class TenantDashboardController {
    private final JdbcTemplate jdbcTemplate;

    public TenantDashboardController(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @GetMapping("/stats")
    @RequirePermission(value = "dashboard.read", dataScope = DataScopeType.TENANT, auditAction = "DASHBOARD_STATS")
    public ApiResponse<Map<String, Object>> stats() {
        Long tenantId = AuthContext.requireTenantId();
        Map<String, Object> result = new LinkedHashMap<>();

        // 活跃会议：状态为 NOT_STARTED 或 IN_PROGRESS 的会议数
        Integer activeMeetingCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(1) FROM meeting WHERE tenant_id=? AND is_deleted=0 AND meeting_status IN ('NOT_STARTED', 'IN_PROGRESS')",
                Integer.class,
                tenantId
        );
        result.put("activeMeetingCount", activeMeetingCount == null ? 0 : activeMeetingCount);

        // 待财务确认：finance_status 为 WAIT_FINANCE_CONFIRM 的会议数
        Integer pendingFinanceCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(1) FROM finance_payment WHERE tenant_id=? AND is_deleted=0 AND payment_status='SUBMITTED'",
                Integer.class,
                tenantId
        );
        result.put("pendingFinanceCount", pendingFinanceCount == null ? 0 : pendingFinanceCount);

        // 待审核任务数
        Integer pendingAuditCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(1) FROM audit_task WHERE tenant_id=? AND is_deleted=0 AND status='PENDING'",
                Integer.class,
                tenantId
        );
        result.put("pendingAuditCount", pendingAuditCount == null ? 0 : pendingAuditCount);

        return ApiResponse.success(result);
    }
}
