package com.honey.honey.controller;

import com.honey.honey.dto.UserCheckDto;
import com.honey.honey.model.UserA;
import com.honey.honey.model.UserB;
import com.honey.honey.model.UserD;
import com.honey.honey.repository.PaymentRepository;
import com.honey.honey.repository.UserARepository;
import com.honey.honey.repository.UserBRepository;
import com.honey.honey.repository.UserDRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * Controller for user check endpoint (open endpoint for external applications).
 * Path token is validated against app.check-user.token (APP_CHECK_USER_TOKEN). No user auth.
 */
@Slf4j
@RestController
@RequestMapping("/api/check_user")
@RequiredArgsConstructor
public class UserCheckController {

    @Value("${app.check-user.token:}")
    private String expectedToken;

    private final UserARepository userARepository;
    private final UserBRepository userBRepository;
    private final UserDRepository userDRepository;
    private final PaymentRepository paymentRepository;

    /**
     * Gets user information by Telegram ID.
     * Path: /api/check_user/{token}/{telegramId}. Token must match APP_CHECK_USER_TOKEN.
     *
     * @param token      Secret token from path (must match config)
     * @param telegramId The Telegram ID of the user
     * @return 200 with user info (found=true) or 200 with found=false when user not found; 403 if token invalid
     */
    @GetMapping("/{token}/{telegramId}")
    public ResponseEntity<UserCheckDto> checkUser(@PathVariable String token, @PathVariable Long telegramId) {
        if (expectedToken.isEmpty() || !expectedToken.equals(token)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        try {
            // Find user by telegram_id
            Optional<UserA> userAOpt = userARepository.findByTelegramId(telegramId);
            
            if (userAOpt.isEmpty()) {
                log.debug("User not found for telegramId={}", telegramId);
                UserCheckDto notFoundResponse = UserCheckDto.builder().found(false).build();
                return ResponseEntity.ok(notFoundResponse);
            }
            
            UserA userA = userAOpt.get();
            Integer userId = userA.getId();
            
            // Get balance_a from db_users_b
            Optional<UserB> userBOpt = userBRepository.findById(userId);
            Long balanceA = userBOpt.map(UserB::getBalanceA).orElse(0L);
            // Convert to tickets (balance_a / 1,000,000)
            Double tickets = balanceA / 1_000_000.0;
            
            // Get referer_id_1 from db_users_d
            Optional<UserD> userDOpt = userDRepository.findById(userId);
            Integer refererId = userDOpt.map(UserD::getRefererId1).orElse(0);
            // Return 0 if refererId is 0 or negative (not set)
            if (refererId <= 0) {
                refererId = 0;
            }
            
            // Sum completed payments stars_amount
            Integer depositTotal = paymentRepository.sumCompletedStarsAmountByUserId(userId);
            
            // Build response
            UserCheckDto response = UserCheckDto.builder()
                    .found(true)
                    .dateReg(userA.getDateReg())
                    .tickets(tickets)
                    .depositTotal(depositTotal)
                    .refererId(refererId)
                    .build();
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Error checking user for telegramId={}", telegramId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}

