const express = require('express');

const InquiriesService = require('../services/inquiries');
const NewsletterSubscribersService = require('../services/newsletter_subscribers');
const wrapAsync = require('../helpers').wrapAsync;

const router = express.Router();

const inquiryTypes = new Set(['contact_message', 'request_samples', 'get_a_quote', 'partner_with_us']);
const buyerTypes = new Set(['roaster', 'importer', 'distributor', 'specialty_buyer', 'wholesaler', 'other']);
const incoterms = new Set(['fob', 'cif', 'cfr', 'exw', 'dap', 'other']);
const contactMethods = new Set(['email', 'phone', 'whatsapp']);
const newsletterSources = new Set(['home_footer', 'home_cta', 'contact_page', 'popup', 'other']);

const isValidEmail = (value) => /\S+@\S+\.\S+/.test(value || '');

const badRequest = (message) => {
  const error = new Error(message);
  error.code = 400;
  return error;
};

router.post(
  '/inquiry',
  wrapAsync(async (req, res) => {
    const data = req.body && req.body.data ? req.body.data : {};

    if (!data.full_name || !data.email || !data.company_name || !data.country || !data.message) {
      throw badRequest('Full name, email, company name, country, and message are required.');
    }

    if (!isValidEmail(data.email)) {
      throw badRequest('A valid email address is required.');
    }

    if (data.inquiry_type && !inquiryTypes.has(data.inquiry_type)) {
      throw badRequest('Invalid inquiry type.');
    }

    if (data.buyer_type && !buyerTypes.has(data.buyer_type)) {
      throw badRequest('Invalid buyer type.');
    }

    if (data.incoterm && !incoterms.has(data.incoterm)) {
      throw badRequest('Invalid incoterm.');
    }

    if (data.preferred_contact_method && !contactMethods.has(data.preferred_contact_method)) {
      throw badRequest('Invalid preferred contact method.');
    }

    if (data.target_volume_kg !== undefined && data.target_volume_kg !== null && Number.isNaN(Number(data.target_volume_kg))) {
      throw badRequest('Target volume must be a number.');
    }

    await InquiriesService.create({
      inquiry_type: data.inquiry_type || 'contact_message',
      status: 'new',
      full_name: data.full_name,
      email: data.email,
      phone: data.phone || null,
      company_name: data.company_name,
      country: data.country,
      buyer_type: data.buyer_type || 'other',
      message: data.message,
      target_volume_kg:
        data.target_volume_kg !== undefined && data.target_volume_kg !== null && data.target_volume_kg !== ''
          ? Number(data.target_volume_kg)
          : null,
      incoterm: data.incoterm || 'fob',
      preferred_contact_method: data.preferred_contact_method || 'email',
      submitted_at: new Date(),
    });

    res.status(200).send({ success: true });
  }),
);

router.post(
  '/newsletter',
  wrapAsync(async (req, res) => {
    const data = req.body && req.body.data ? req.body.data : {};

    if (!data.email || !isValidEmail(data.email)) {
      throw badRequest('A valid email address is required.');
    }

    if (data.source && !newsletterSources.has(data.source)) {
      throw badRequest('Invalid newsletter source.');
    }

    await NewsletterSubscribersService.create({
      email: data.email,
      full_name: data.full_name || null,
      company_name: data.company_name || null,
      country: data.country || null,
      source: data.source || 'other',
      is_confirmed: false,
      subscribed_at: new Date(),
    });

    res.status(200).send({ success: true });
  }),
);

router.use('/', require('../helpers').commonErrorHandler);

module.exports = router;
