package kr.iotdoor.boot.service;

import kr.iotdoor.boot.mapper.ContactMapper;
import kr.iotdoor.boot.model.contact.ContactRequest;
import kr.iotdoor.boot.model.contact.ContactSubmission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class ContactSubmissionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContactSubmissionService.class);

    private final ContactMapper contactMapper;

    public ContactSubmissionService(ContactMapper contactMapper) {
        this.contactMapper = contactMapper;
    }

    public ContactSubmission submit(ContactRequest request) {
        ContactSubmission submission = new ContactSubmission();
        submission.setContactIdntfNo(UUID.randomUUID().toString().replace("-", ""));
        submission.setName(request.name().trim());
        submission.setEmail(request.email().trim());
        submission.setPhone(request.phone().trim());
        submission.setSubject(request.subject().trim());
        submission.setMessage(request.message().trim());
        submission.setSubmittedAt(LocalDateTime.now());

        contactMapper.insertContact(submission);

        LOGGER.info("Contact inquiry received from {} <{}> / subject={}",
            submission.getName(), submission.getEmail(), submission.getSubject());

        return submission;
    }

    public List<ContactSubmission> recentSubmissions(int limit) {
        return contactMapper.selectRecentContacts(limit);
    }

    public List<ContactSubmission> findAll() {
        return contactMapper.selectAllContacts();
    }

    public int count() {
        return contactMapper.selectContactCount();
    }
}
