package de.assecutor.votianlt.service;

import de.assecutor.votianlt.model.InvoiceTemplate;
import de.assecutor.votianlt.repository.InvoiceTemplateRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class InvoiceTemplateService {

    private final InvoiceTemplateRepository invoiceTemplateRepository;

    /**
     * Save or update the invoice template for a user
     */
    public InvoiceTemplate saveTemplate(String userId, String templateData) {
        Optional<InvoiceTemplate> existing = invoiceTemplateRepository.findByUserId(userId);

        if (existing.isPresent()) {
            InvoiceTemplate template = existing.get();
            template.updateTemplate(templateData);
            return invoiceTemplateRepository.save(template);
        } else {
            InvoiceTemplate newTemplate = new InvoiceTemplate(userId, "Standard", templateData);
            return invoiceTemplateRepository.save(newTemplate);
        }
    }

    /**
     * Get the invoice template for a user
     */
    public Optional<InvoiceTemplate> getTemplateByUserId(String userId) {
        return invoiceTemplateRepository.findByUserId(userId);
    }

    /**
     * Check if a template exists for a user
     */
    public boolean hasTemplate(String userId) {
        return invoiceTemplateRepository.existsByUserId(userId);
    }

    /**
     * Delete the template for a user
     */
    public void deleteTemplate(String userId) {
        invoiceTemplateRepository.deleteByUserId(userId);
    }
}
