package de.assecutor.votianlt.pages.service;

import de.assecutor.votianlt.model.UserInvoiceData;
import de.assecutor.votianlt.repository.UserInvoiceDataRepository;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserInvoiceDataService {

    private final UserInvoiceDataRepository userInvoiceDataRepository;

    public UserInvoiceDataService(UserInvoiceDataRepository userInvoiceDataRepository) {
        this.userInvoiceDataRepository = userInvoiceDataRepository;
    }

    public Optional<UserInvoiceData> findByUserId(ObjectId userId) {
        return userInvoiceDataRepository.findByUserId(userId);
    }

    public UserInvoiceData save(UserInvoiceData userInvoiceData) {
        userInvoiceData.updateTimestamp();
        return userInvoiceDataRepository.save(userInvoiceData);
    }

    public UserInvoiceData createOrUpdate(ObjectId userId, boolean billingEnabled, String prefix, String ustId,
                                         String taxNumber, String bankName, String iban, String taxRate,
                                         String introText, String paymentTerms) {
        // If billing is disabled, delete any existing record and return null
        if (!billingEnabled) {
            deleteByUserId(userId);
            return null;
        }

        // Otherwise, create or update the record
        UserInvoiceData invoiceData = findByUserId(userId).orElse(new UserInvoiceData());

        invoiceData.setUserId(userId);
        invoiceData.setBillingEnabled(billingEnabled);
        invoiceData.setPrefix(prefix);
        invoiceData.setUstId(ustId);
        invoiceData.setTaxNumber(taxNumber);
        invoiceData.setBankName(bankName);
        invoiceData.setIban(iban);
        invoiceData.setTaxRate(taxRate);
        invoiceData.setIntroText(introText);
        invoiceData.setPaymentTerms(paymentTerms);

        return save(invoiceData);
    }

    public void deleteByUserId(ObjectId userId) {
        userInvoiceDataRepository.deleteByUserId(userId);
    }
}