package com.example.skychasemk.services;

import com.example.skychasemk.dto.PaymentDTO;
import com.example.skychasemk.model.ApplicationUser;
import com.example.skychasemk.model.Payment;
import com.example.skychasemk.model.Booking;
import com.example.skychasemk.repository.ApplicationUserRepository;
import com.example.skychasemk.repository.BookingRepository;
import com.example.skychasemk.repository.PaymentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

import static com.example.skychasemk.model.Payment.PaymentMethod.CREDIT;
import static com.example.skychasemk.model.Payment.PaymentStatus.COMPLETED;

@Service
public class PaymentService {

    @Autowired
    private PaymentRepository paymentRepository;
    @Autowired
    ApplicationUserRepository userRepository;
    @Autowired
    BookingRepository bookingRepository;

    // Get all payments
    public List<Payment> getAllPayments() {
        return paymentRepository.findAll();
    }

    // Get payment by ID
    public Optional<Payment> getPaymentById(Integer paymentID) {
        return paymentRepository.findById(paymentID);
    }


    // Update an existing payment
    public Payment updatePayment(Integer paymentID, Payment payment) {
        if (paymentRepository.existsById(paymentID)) {
            payment.setPaymentID(paymentID);
            return paymentRepository.save(payment);
        } else {
            throw new RuntimeException("Payment not found with id " + paymentID);
        }
    }

    // Delete a payment
    public void deletePayment(Integer paymentID) {
        paymentRepository.deleteById(paymentID);
    }

    public Payment createTransaction(PaymentDTO dto){
        //ApplicationUser user = userRepository.findById(dto.getUserID())
        //        .orElseThrow(() -> new RuntimeException("User not found"));

        Payment payment = new Payment();
        payment.setAmount(dto.getAmount());
        payment.setBookingID(dto.getBookingID());
        //payment.setUserID(dto.getUserID());
        payment.setStatus(COMPLETED);
        payment.setMethod(CREDIT);
        payment.setTransactionDate(LocalDate.now());
        return paymentRepository.save(payment);
    }

    public Payment savePayment(Payment payment) {
        return paymentRepository.save(payment);
    }
}

