const { body } = require('express-validator');
const {
  applyHost,
  manageApplication,
  getApplicationById,
  getMyApplications,
  updateBasicInfo,
  getIncompleteListings,
  sendEmailFromBackOffice,
} = require('../../../controllers/host/v1.1/apply');
const { isAuth, validation } = require('../../../middlewares');
const { jsonParser } = require('../../../helpers');

const router = require('express').Router();

router.post(
  '/',
  jsonParser,
  [
    body('data.listingName').notEmpty(),
    body('data.description').notEmpty(),
    body('data.hostingType').isIn(['Individual', 'Business', 'Corporation']),
    body('data.fullname').isString().optional(),
    body('data.businessName').isString().optional(),
    body('data.businessAddress').isString().optional(),
    body('data.listingType').isIn(['Public', 'Private']),
    body('data.location').isString(),
    body('data.latitude').notEmpty(),
    body('data.longitude').notEmpty(),
    body('data.tents').isNumeric().optional(),
    body('data.vans').isNumeric().optional(),
    body('data.extraGuestFee').isDecimal().optional({
      values: 'falsy',
    }),
    body('data.cleaningFee').isDecimal(),
    body('data.smokingPolicy').optional({ values: 'falsy' }),
    body('data.petsPolicy').optional({ values: 'falsy' }),
    body('data.quietHoursStart').isString(),
    body('data.quietHoursEnd').isString(),
    body('data.securityDeposit').isBoolean(),
    body('data.securityDepositPrice').custom((value, { req }) => {
      const { securityDeposit, securityDepositPrice } = req.body.data;
      if (securityDeposit === true || securityDeposit === 'true') {
        if (
          securityDepositPrice === undefined ||
          securityDepositPrice === null ||
          securityDepositPrice === '' ||
          isNaN(Number(securityDepositPrice))
        ) {
          throw new Error('securityDepositPrice is required when securityDeposit is true.');
        }
      }
      return true;
    }),
    body('data.approval').isIn(['Auto', 'Manual']),
    body('data.addressCountry').notEmpty(),
    body('data.addressStreet').notEmpty(),
    body('data.addressApt').isString().optional(),
    body('data.addressCity').notEmpty(),
    body('data.addressState').notEmpty(),
    body('data.addressZip').notEmpty(),
    body('data.paymentMethod')
      .optional()
      .custom((value, { req }) => {
        const { paymentMethod } = req.body.data;

        for (const field of ['bankName', 'bankAccountName', 'bankAccountNumber']) {
          if (!paymentMethod[field]) {
            throw new Error(`${field} is required for Debit/Credit payment method.`);
          }
        }

        return true;
      }),
    body().custom((value, { req }) => {
      const files = req.files || {};
      const listingImgs = files.listingImgs || [];
      const supportingDocs = files.supportingDocs || [];

      const { data } = req.body;

      const supportingDocTypes = data?.supportingDocTypes ?? [];

      const listingImageCategories = data?.listingImageCategories ?? [];

      if (listingImgs?.length === 0) {
        throw new Error('Listing images are required.');
      }
      if (listingImageCategories.length !== listingImgs.length) {
        throw new Error(
          'Listing image categories are required and should match the number of files.',
        );
      }

      // if (!supportingDocTypes || supportingDocTypes.length === 0) {
      // 	throw new Error('Supporting document types are required.');
      // }
      if (supportingDocTypes.length !== supportingDocs.length) {
        throw new Error(
          'Supporting document types are required and should match the number of files.',
        );
      }

      const hostingType = data.hostingType;

      const requiredFiles = {
        Individual: {
          // files: ['Proof of Ownership/Lease'],
          fields: ['fullname', 'birthDate', 'birthPlace'],
        },
        Business: {
          // files: [
          // 	'Business Permit',
          // 	'DTI/SEC Registration',
          // 	'Bureau of Internal Revenue', //?same
          // 	'BIR Certificate of Registration', //?same
          // ],
          fields: ['businessName', 'businessAddress', 'businessType'],
        },
        // Corporation: {
        // 	files: ['SEC Certificate of Incorporation', 'Articles of Incorporation', 'Company Profile'],
        // },
      };

      for (const key in requiredFiles) {
        if (hostingType === key) {
          const { files: requiredDocs, fields: requiredFields = [] } = requiredFiles[key];

          //Use if you want to check the number of files uploaded

          // if (key === 'Individual') {
          // 	if (supportingDocTypes.length < 2) {
          // 		throw new Error('Missing required documents for Individual hosting type.');
          // 	}
          // }
          // for (const doc of requiredDocs) {
          // 	if (!supportingDocTypes.includes(doc)) {
          // 		throw new Error(`Missing required document: ${doc}`);
          // 	}
          // }

          for (const field of requiredFields) {
            if (!data[field] || data[field].trim() === '') {
              throw new Error(`Missing required field: ${field}`);
            }
          }
        }
      }

      if (data.listingType === 'Public') {
        if (!data?.spots || data?.spots?.length === 0 || !Array.isArray(data.spots)) {
          throw new Error('Missing or invalid required field: listing spots');
        }
      }

      return true;
    }),
    body().custom((value, { req }) => {
      const jsonFields = [
        'amenities',
        'services',
        'listingImageCategories',
        'supportingDocTypes',
        'addOns',
        'discounts',
        'spots',
      ];

      const { data } = req.body;

      for (const field of jsonFields) {
        if (data[field]) {
          try {
            if (!Array.isArray(data[field])) {
              throw new Error(`${field} must be an array.`);
            }
          } catch (error) {
            throw new Error(`${field} must be a valid JSON array.`);
          }
        }
      }
      return true;
    }),
    validation,
  ],
  isAuth,
  applyHost,
);

router.post(
  '/basic-info',
  body('emailAddress').optional().isEmail(),
  body('phoneNo').optional().notEmpty(),
  body('firstname').optional().notEmpty(),
  body('lastname').optional().notEmpty(),
  validation,
  isAuth,
  updateBasicInfo,
);

router.get('/incomplete', isAuth, getIncompleteListings);

router.patch(
  '/:listingId',
  [body('status').isIn(['Approved', 'Declined']), validation],
  manageApplication,
);

router.get('/:applicationId', isAuth, getApplicationById);
router.get('/', isAuth, getMyApplications);

router.post('/send-email-from-back-office', sendEmailFromBackOffice);

module.exports = router;
