import ContactMessage from "../models/service/contactmessage.js";

class ContactService {

    async addContactMessage(email, name, message, acceptDataSave) {
        if (acceptDataSave && !email) {
            throw new Error('emailrequired');
        }
        if (!acceptDataSave) {
            name = '';
            email = '';
        }
        await ContactMessage.create({
            email,
            name,
            message,
            allowDataSave: acceptDataSave
        });
    }

    async getContactById(id) {
        const contact = await ContactMessage.findByPk(id);
        if (!contact) {
            const error = new Error('Contact not found');
            error.status = 404;
            throw error;
        }
        return contact;
    }

    async saveAnswer(contact, answer) {
        contact.answer = answer;
        contact.answeredAt = new Date();
        contact.isFinished = true;
        await contact.save();
    }
}

export default new ContactService();
