package com.web.service;

import com.web.entity.Cart;
import com.web.entity.HistoryPay;
import com.web.entity.Invoice;
import com.web.entity.InvoiceDetail;
import com.web.entity.User;
import com.web.enums.Paytype;
import com.web.repository.*;
import com.web.utils.StatusUtils;
import com.web.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Time;
import java.util.List;

@Service
public class InvoiceService {

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private StatusRepository statusRepository;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private InvoiceRepository invoiceRepository;

    @Autowired
    private InvoiceDetailRepository invoiceDetailRepository;

    @Autowired
    private HistoryPayRepository historyPayRepository;

    /**
     * Tạo invoice, hỗ trợ user hoặc guest
     */
    public Invoice createInvoice(Paytype paytype, String fullname, String phone, String address, String note,
                                 User user, List<Cart> cartList) {

        // Nếu cartList null và user != null thì lấy từ DB
        if ((cartList == null || cartList.isEmpty()) && user != null) {
            cartList = cartRepository.findByUser(user.getId());
        }

        if (cartList == null || cartList.isEmpty()) {
            throw new IllegalArgumentException("Cart trống, không thể tạo invoice!");
        }

        double total = cartList.stream().mapToDouble(c -> c.getQuantity() * c.getProduct().getPrice()).sum();

        Invoice invoice = new Invoice();
        invoice.setReceiverName(fullname);
        invoice.setPhone(phone);
        invoice.setAddress(address);
        invoice.setNote(note);
        invoice.setCreatedDate(new Date(System.currentTimeMillis()));
        invoice.setCreatedTime(new Time(System.currentTimeMillis()));
        invoice.setUser(user);
        invoice.setTotalAmount(total);
        invoice.setPayType(paytype);
        invoice.setStatus(statusRepository.findById(StatusUtils.DANG_CHO_XAC_NHAN).get());

        Invoice savedInvoice = invoiceRepository.save(invoice);

        // Lưu chi tiết đơn
        for (Cart c : cartList) {
            InvoiceDetail detail = new InvoiceDetail();
            detail.setInvoice(savedInvoice);
            detail.setProduct(c.getProduct());
            detail.setQuantity(c.getQuantity());
            detail.setPrice(c.getProduct().getPrice());
            invoiceDetailRepository.save(detail);

            // Trừ tồn kho
            c.getProduct().setQuantity(c.getProduct().getQuantity() - c.getQuantity());
            productRepository.save(c.getProduct());
        }

        return savedInvoice;
    }

    /**
     * Tạo lịch sử thanh toán
     */
    public HistoryPay createHistoryPay(String orderId, String requestId, Invoice invoice) {
        if (historyPayRepository.findByOrderIdAndRequestId(orderId, requestId).isPresent()) {
            return null;
        }
        HistoryPay historyPay = new HistoryPay();
        historyPay.setInvoice(invoice);
        historyPay.setOrderId(orderId);
        historyPay.setRequestId(requestId);
        historyPay.setTotalAmount(invoice.getTotalAmount());
        historyPay.setCreatedDate(new Date(System.currentTimeMillis()));
        historyPayRepository.save(historyPay);
        return historyPay;
    }
}
