package de.szut.casino.deposit;

import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.checkout.Session;
import com.stripe.param.checkout.SessionCreateParams;
import de.szut.casino.deposit.dto.AmountDto;
import de.szut.casino.deposit.dto.SessionIdDto;
import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DepositController {

    @Value("${stripe.secret.key}")
    private String stripeKey;

    @Value("${app.frontend-host}")
    private String frontendHost;

    private final TransactionService transactionService;

    private final UserService userService;

    public DepositController(TransactionService transactionService, UserService userService) {
        this.transactionService = transactionService;
        this.userService = userService;
    }

    @PostMapping("/deposit/checkout")
    public ResponseEntity<SessionIdDto> checkout(@RequestBody @Valid AmountDto amountDto, @RequestHeader("Authorization") String token) throws StripeException {
        Stripe.apiKey = stripeKey;

        UserEntity user = userService.getCurrentUser();

        SessionCreateParams params = SessionCreateParams.builder()
                .addLineItem(SessionCreateParams.LineItem.builder()
                        .setPriceData(SessionCreateParams.LineItem.PriceData.builder()
                                .setCurrency("EUR")
                                .setUnitAmount((long) amountDto.getAmount() * 100)
                                .setProductData(SessionCreateParams.LineItem.PriceData.ProductData.builder()
                                        .setName("Einzahlung")
                                        .build())
                                .build())
                        .setQuantity(1L)
                        .build())
                .setSuccessUrl(frontendHost + "/home?success=true")
                .setCancelUrl(frontendHost + "/home?success=false")
                .setMode(SessionCreateParams.Mode.PAYMENT)
                .build();

        Session session = Session.create(params);

        transactionService.createTransaction(user, session.getId(), amountDto.getAmount());

        return ResponseEntity.ok(new SessionIdDto(session.getId()));
    }
}

