"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteTicket = exports.replyToTicket = exports.getTicketsQueue = exports.submitEnquiry = void 0;
const database_1 = __importDefault(require("../config/database"));
const response_utils_1 = require("../utils/response.utils");
const email_service_1 = require("../services/email.service");
const logger_1 = require("../config/logger");
// 1. Public: Submit enquiry form (generates ticketNumber)
const submitEnquiry = async (req, res) => {
    try {
        const { name, email, subject, message } = req.body;
        const ticketNumber = `TK-${Date.now().toString().slice(-4)}-${Math.floor(1000 + Math.random() * 9000)}`;
        const enquiry = await database_1.default.contactEnquiry.create({
            data: {
                ticketNumber,
                name,
                email: email.toLowerCase(),
                subject,
                message,
                status: 'PENDING',
            },
        });
        logger_1.logger.info(`New Contact ticket raised: ${ticketNumber} by ${email}`);
        // Send acknowledgement email notification
        await email_service_1.EmailService.sendEmail({
            to: email,
            subject: `Support Request Received - ${ticketNumber}`,
            html: `
        <div style="font-family: sans-serif; padding: 20px; color: #333;">
          <h3>Hello ${name},</h3>
          <p>We have successfully received your support request ticket: <strong>${ticketNumber}</strong>.</p>
          <p>Our Vedic lit specialist team will review your message and reply within 24 business hours.</p>
          <hr />
          <p><strong>Subject:</strong> ${subject}</p>
          <p><strong>Message:</strong> ${message}</p>
        </div>
      `,
        });
        return (0, response_utils_1.sendSuccess)(res, 'Support request ticket created successfully', { ticketNumber, enquiry });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to raise contact ticket', error.message, 500);
    }
};
exports.submitEnquiry = submitEnquiry;
// 2. Admin: List tickets queue
const getTicketsQueue = async (req, res) => {
    try {
        if (res.locals.userRole !== 'ADMIN' && req.user?.role !== 'ADMIN') {
            return (0, response_utils_1.sendError)(res, 'Forbidden', null, 403);
        }
        const tickets = await database_1.default.contactEnquiry.findMany({
            orderBy: { createdAt: 'desc' },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Tickets list retrieved successfully', { tickets });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to fetch tickets queue', error.message, 500);
    }
};
exports.getTicketsQueue = getTicketsQueue;
// 3. Admin: Update ticket notes & send reply
const replyToTicket = async (req, res) => {
    try {
        const { id } = req.params;
        const { response, adminNotes, status } = req.body;
        if (res.locals.userRole !== 'ADMIN' && req.user?.role !== 'ADMIN') {
            return (0, response_utils_1.sendError)(res, 'Forbidden', null, 403);
        }
        const ticket = await database_1.default.contactEnquiry.findUnique({ where: { id } });
        if (!ticket)
            return (0, response_utils_1.sendError)(res, 'Ticket not found', null, 404);
        const updated = await database_1.default.contactEnquiry.update({
            where: { id },
            data: {
                response: response || undefined,
                adminNotes: adminNotes || undefined,
                status: status || undefined,
            },
        });
        // Send email notification reply to customer
        if (response) {
            await email_service_1.EmailService.sendEmail({
                to: ticket.email,
                subject: `Re: ${ticket.subject} [${ticket.ticketNumber}]`,
                html: `
          <div style="font-family: sans-serif; padding: 20px; color: #333; line-height: 1.5;">
            <p>Hello ${ticket.name},</p>
            <p>An administrator has responded to your ticket <strong>${ticket.ticketNumber}</strong>:</p>
            <div style="background-color: #f9f9f9; padding: 15px; border-left: 4px solid #701a08; margin: 15px 0;">
              ${response}
            </div>
            <p>Best regards,<br />Customer Care Team<br />Indian Books Worldwide</p>
          </div>
        `,
            });
            logger_1.logger.info(`Replied to ticket ${ticket.ticketNumber} and sent email notification.`);
        }
        return (0, response_utils_1.sendSuccess)(res, 'Ticket reply submitted successfully', { ticket: updated });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to submit ticket reply', error.message, 500);
    }
};
exports.replyToTicket = replyToTicket;
// 4. Admin: Delete ticket
const deleteTicket = async (req, res) => {
    try {
        const { id } = req.params;
        if (res.locals.userRole !== 'ADMIN' && req.user?.role !== 'ADMIN') {
            return (0, response_utils_1.sendError)(res, 'Forbidden', null, 403);
        }
        await database_1.default.contactEnquiry.delete({ where: { id } });
        return (0, response_utils_1.sendSuccess)(res, 'Support ticket deleted successfully');
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to delete ticket', error.message, 500);
    }
};
exports.deleteTicket = deleteTicket;
//# sourceMappingURL=contact.controller.js.map