package com.rit.canteen.sales.controller;

import com.rit.canteen.sales.model.TokenTransaction;
import com.rit.canteen.sales.model.User;
import com.rit.canteen.sales.service.TokenService;
import com.rit.canteen.sales.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/wallet")
public class WalletController {

    @Autowired
    private com.rit.canteen.sales.repository.UserRepository userRepository;

    @Autowired
    private com.rit.canteen.sales.service.TokenService tokenService;

    @GetMapping("/balance/{userId}")
    public ResponseEntity<?> getBalance(@PathVariable Long userId) {
        try {
            User user = userRepository.findById(userId).orElse(null);
            
            if (user == null) return ResponseEntity.notFound().build();
            return ResponseEntity.ok(Map.of("balance", user.getRitzTokenBalance()));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("error", e.getMessage()));
        }
    }

    @GetMapping("/users")
    public ResponseEntity<List<Map<String, Object>>> getUsers() {
        List<User> users = userRepository.findAll();
        List<Map<String, Object>> userList = users.stream().map(user -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("name", user.getName());
            map.put("mobileNumber", user.getMobileNumber());
            map.put("ritzTokenBalance", user.getRitzTokenBalance());
            return map;
        }).collect(Collectors.toList());
        return ResponseEntity.ok(userList);
    }

    @GetMapping("/transactions/{userId}")
    public ResponseEntity<List<TokenTransaction>> getTransactions(@PathVariable Long userId) {
        return ResponseEntity.ok(tokenService.getTransactions(userId));
    }

    @PostMapping("/topup")
    public ResponseEntity<?> topUp(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            BigDecimal amount = new BigDecimal(request.get("amount").toString());
            String ref = request.getOrDefault("referenceId", "TOPUP-" + System.currentTimeMillis()).toString();

            User updatedUser = tokenService.topUp(userId, amount, ref);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "newBalance", updatedUser.getRitzTokenBalance(),
                "message", "Successfully added " + amount + " Ritz Tokens"
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("error", e.getMessage()));
        }
    }

    @GetMapping("/transactions/all")
    public ResponseEntity<List<TokenTransaction>> getAllTransactions() {
        return ResponseEntity.ok(tokenService.getAllTransactions());
    }

    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getStats() {
        return ResponseEntity.ok(tokenService.getGlobalStats());
    }

    @GetMapping("/circulation")
    public ResponseEntity<org.springframework.data.domain.Page<com.rit.canteen.sales.model.TokenUnit>> getCirculation(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        return ResponseEntity.ok(tokenService.getAllCirculation(page, size));
    }
}
