package com.honey.honey.controller;

import com.honey.honey.dto.CreatePayoutRequest;
import com.honey.honey.dto.ErrorResponse;
import com.honey.honey.dto.PayoutHistoryEntryDto;
import com.honey.honey.dto.PayoutResponse;
import com.honey.honey.model.Payout;
import com.honey.honey.model.UserA;
import com.honey.honey.security.UserContext;
import com.honey.honey.service.PayoutService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/payouts")
@RequiredArgsConstructor
public class PayoutController {

    private final PayoutService payoutService;

    /**
     * Creates a payout request for the current user.
     * Validates input and deducts balance if validation passes.
     */
    @PostMapping
    public ResponseEntity<?> createPayout(@RequestBody CreatePayoutRequest request) {
        try {
            UserA user = UserContext.get();
            Payout payout = payoutService.createPayout(user.getId(), request);
            PayoutResponse response = payoutService.toResponse(payout);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            log.warn("Payout validation failed: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(new ErrorResponse(e.getMessage()));
        } catch (IllegalStateException e) {
            log.error("Payout creation failed: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ErrorResponse(e.getMessage()));
        }
    }


    /**
     * Gets the last 20 payout history entries for the current user.
     * 
     * @param timezone Optional timezone (e.g., "Europe/London"). If not provided, uses UTC.
     */
    @GetMapping("/history")
    public List<PayoutHistoryEntryDto> getUserPayoutHistory(
            @RequestParam(required = false) String timezone) {
        UserA user = UserContext.get();
        String languageCode = user.getLanguageCode();
        if (languageCode == null || languageCode.isEmpty() || "XX".equals(languageCode)) {
            languageCode = "EN";
        }
        return payoutService.getUserPayoutHistory(user.getId(), timezone, languageCode);
    }
}

