'use server';

import { IContactFormValues } from '@/components/form/ContactForm/ContactForm';
import { verifyRecaptcha } from './utils/verifyRecaptcha';
import fetcher from './fetcher';

const submitForm = async (values: IContactFormValues): Promise<IResponse> => {
  try {
    const captchaToken = await verifyRecaptcha(values.recaptchaToken);
    if (!captchaToken) {
      throw new Error('Invalid captcha token');
    }
    const payload = {
      title: values.title,
      firstName: values.firstName,
      lastName: values.lastName,
      middleName: '',
      countryCode: values.dialCode,
      mobileNumber: values.mobileNumber,
      email: values.email,
      source: 'WebToLead',
      channelType: 'WebToLead',
      channelName: '',
      countryOfResidence: values.residence,
      propertyType: values.unitType,
      unitSize: values.unitSize,
      budget: values.budget,
      buyingPurpose: values.purpose,
      project: 'JN',
      companyName: '',
      formName: ''
    };

    await fetcher(`/contacts`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ data: payload })
    });
    return { success: true };
  } catch (error: any) {
    console.error('=> Error submitting lead', error);
    return { success: false, code: error?.message };
  }
};

export default submitForm;
