const HttpException = require('../../../utils/HttpException.js');

exports.validateStoreVendorHistoryRequest = (body) => {
    const { simrs_type, vendor_id, vendor_impression, status, contract_date, contract_expired_date } = body;

    const errors = {};

    if (!simrs_type || simrs_type.trim() === '') {
        errors.simrs_type = ['simrs type is required'];
    } else if (!['vendor', 'gratis', 'in house'].includes(simrs_type.trim().toLowerCase())) {
        errors.simrs_type = ['Simrs type must be either "vendor", "gratis", or "in house"'];
    }

    // if (!vendor_id || vendor_id.trim() === '') {
    //     errors.vendor_id = ['Vendor id is required'];
    // }

    // if (!vendor_impression || vendor_impression.trim() === '') {
    //     errors.vendor_impression = ['Vendor impression is required'];
    // }

    if (!['active', 'inactive'].includes(status.trim().toLowerCase())) {
        errors.status = ['Status must be either "active" or "inactive"'];
    }

    // if (!status || status.trim() === '') {
    //     errors.status = ['Status is required'];
    // } else if (!['active', 'inactive'].includes(status.trim().toLowerCase())) {
    //     errors.status = ['Status must be either "active" or "inactive"'];
    // }

    if (contract_date !== null && contract_date !== '' && isNaN(Date.parse(contract_date))) {
        errors.contract_date = ['Contract date must be a valid date'];
    }


    // if (!contract_date || contract_date.trim() === '') {
    //     errors.contract_date = ['Contract date is required'];
    // } else if (isNaN(Date.parse(contract_date))) {
    //     errors.contract_date = ['Contract date must be a valid date'];
    // }

    if (contract_expired_date !== null && contract_expired_date !== '' && isNaN(Date.parse(contract_expired_date))) {
        errors.contract_expired_date = ['Contract expired date must be a valid date'];
    }

    // if (!contract_expired_date || contract_expired_date.trim() === '') {
    //     errors.contract_expired_date = ['Contract expired date is required'];
    // } else if (isNaN(Date.parse(contract_expired_date))) {
    //     errors.contract_expired_date = ['Contract expired date must be a valid date'];
    // }

    if (
        !errors.contract_date &&
        !errors.contract_expired_date &&
        new Date(contract_expired_date) <= new Date(contract_date)
    ) {
        errors.contract_expired_date = ['Contract expired date must be after contract date'];
    }

    if (Object.keys(errors).length > 0) {
        throw new HttpException(errors, 422);
    }

    return {
        simrs_type: simrs_type.trim(),
        vendor_id: vendor_id ? vendor_id.trim() : null,
        vendor_impression: vendor_impression ? vendor_impression.trim() : null,
        status: status.trim().toLowerCase(),
        contract_date: contract_date ? new Date(contract_date) : null,
        contract_expired_date: contract_expired_date ? new Date(contract_expired_date) : null,
    };
};