package ru.soune.nocopy.controller;

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 ru.soune.nocopy.dto.search.GlobalSearchStartResponse;
import ru.soune.nocopy.entity.payment.Payment;
import ru.soune.nocopy.exception.PaymentNotFoundException;
import ru.soune.nocopy.exception.TariffNotFoundException;
import ru.soune.nocopy.exception.UserNotFoundException;
import ru.soune.nocopy.service.payment.PaymentService;
import ru.soune.nocopy.service.register.AuthService;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/payments")
@RequiredArgsConstructor
@Slf4j
public class PaymentController {

    private final PaymentService paymentService;

    private final AuthService authService;

    @PostMapping("/create")
    public ResponseEntity<?> createPayment(@RequestParam String email, @RequestParam Long tariffId,
                                           @RequestParam String operationType, @RequestParam String operationUuid) {
        try {
            Payment payment = paymentService.createPayment(email, tariffId, operationType, operationUuid);

            return ResponseEntity.ok(payment);
        } catch (TariffNotFoundException e) {
            return ResponseEntity
                    .status(HttpStatus.NOT_FOUND)
                    .body(Map.of("error", "Tariff not found", "message", e.getMessage()));
        } catch (UserNotFoundException e) {
            return ResponseEntity
                    .status(HttpStatus.NOT_FOUND)
                    .body(Map.of("error", "User not found", "message", e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "Internal server error", "message", e.getMessage()));
        }
    }

    @PostMapping("webhook/yookassa")
    public void handleYooKassaNotification(@RequestBody Map<String, Object> notification) {
        try {
            paymentService.handlePaymentNotification(notification);
            log.info("Notification from yookassa: " + notification);
        } catch (PaymentNotFoundException e) {
            log.error("Error processing payment notification", e);
        }
    }

    @PostMapping("/auto-renewal")
    public ResponseEntity<?> disableAutoRenewal(@RequestParam(value = "renewal") Boolean renewal,
            @RequestHeader(value = "Authorization", required = false) String tokenHeader) {
        try {
            if (tokenHeader == null || tokenHeader.isBlank()) {
                Map<String, Object> errorData = new HashMap<>();
                errorData.put("token", tokenHeader);

                return ResponseEntity.ok().body(Map.of("error", errorData));
            }

            paymentService.changeAutoRenewal(authService.useUserAuthToken(tokenHeader), renewal);
            return ResponseEntity.ok(Map.of("message", "Auto-renewal changed:" + renewal));
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of("error", e.getMessage()));
        }
    }

    @DeleteMapping("/methods/{paymentMethodId}")
    public ResponseEntity<?> deletePaymentMethod(@RequestHeader(value = "Authorization", required = false) String tokenHeader,
                                                 @PathVariable String paymentMethodId) {
        try {
            if (tokenHeader == null || tokenHeader.isBlank()) {
                Map<String, Object> errorData = new HashMap<>();
                errorData.put("token", tokenHeader);

                return ResponseEntity.ok().body(Map.of("error", errorData));
            }

            paymentService.deletePaymentMethod(authService.useUserAuthToken(tokenHeader), paymentMethodId);
            return ResponseEntity.ok(Map.of("message", "Payment method deleted"));
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of("error", e.getMessage()));
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Map.of("error", e.getMessage()));
        }
    }

    @GetMapping("/methods")
    public ResponseEntity<?> getPaymentMethods(@RequestHeader(value = "Authorization", required = false) String tokenHeader) {
        try {
            if (tokenHeader == null || tokenHeader.isBlank()) {
                Map<String, Object> errorData = new HashMap<>();
                errorData.put("token", tokenHeader);

                return ResponseEntity.ok().body(Map.of("error", errorData));
            }

            return ResponseEntity.ok(paymentService.getUserPaymentMethods(
                    authService.useUserAuthToken(tokenHeader)));
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of("error", e.getMessage()));
        }
    }
}
