package com.honey.honey.controller;

import com.honey.honey.dto.AdminProjectStatisticsDto;
import com.honey.honey.model.Payment;
import com.honey.honey.model.Payout;
import com.honey.honey.repository.PaymentRepository;
import com.honey.honey.repository.PayoutRepository;
import com.honey.honey.repository.UserARepository;
import com.honey.honey.repository.UserBRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;

@RestController
@RequestMapping("/api/admin/statistics")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdminStatisticsController {

    private final UserARepository userARepository;
    private final UserBRepository userBRepository;
    private final PaymentRepository paymentRepository;
    private final PayoutRepository payoutRepository;

    @GetMapping("/project")
    public ResponseEntity<AdminProjectStatisticsDto> getProjectStatistics() {
        long registered = userARepository.count();
        long subscribed = userARepository.countByBotActiveIsTrue();
        long blocked = userARepository.countByBotActiveIsFalse();
        BigDecimal totalDeposits = paymentRepository.sumUsdAmountByStatus(Payment.PaymentStatus.COMPLETED)
                .orElse(BigDecimal.ZERO);
        BigDecimal totalWithdrawals = payoutRepository.sumUsdAmountByStatus(Payout.PayoutStatus.COMPLETED)
                .orElse(BigDecimal.ZERO);
        long withDeposit = userBRepository.countUsersWithDeposit();

        BigDecimal percent = BigDecimal.ZERO;
        if (registered > 0) {
            percent = BigDecimal.valueOf(withDeposit)
                    .multiply(BigDecimal.valueOf(100))
                    .divide(BigDecimal.valueOf(registered), 2, RoundingMode.HALF_UP);
        }

        AdminProjectStatisticsDto dto = AdminProjectStatisticsDto.builder()
                .registeredUsers(registered)
                .subscribedToBot(subscribed)
                .blockedBot(blocked)
                .totalDepositsUsd(totalDeposits)
                .totalWithdrawalsUsd(totalWithdrawals)
                .usersWithDeposit(withDeposit)
                .depositUserPercent(percent)
                .build();
        return ResponseEntity.ok(dto);
    }
}
