{{#if disclaimer}}// {{{ disclaimer }}}{{#if header}}
{{{header}}}{{/if}}

import * as yup from "yup";{{/if}}

export const {{Name}}SchemaFields = {{{curlyOpen}}}{{#each fields}}
    {{name}}: {{#if typeIsObject}}{{ ../Name }}_{{name}}Schema{{else}}{{#if typeIsArray}}yup.array().of(yup.{{valueType}}{{else}}yup.{{type}}{{/if}}(){{#if typeIsString}}.trim().transform(v => v === '' ? undefined : v){{/if}}{{#if isEnum}}
        {{arrayIndent}}.oneOf({{{enumValues}}}, '{{labelName}}_enum'){{/if}}{{#if minValue}}
        {{arrayIndent}}.min({{minValue}}, '{{labelName}}_minValue'){{/if}}{{#if maxValue}}
        {{arrayIndent}}.max({{maxValue}}, '{{labelName}}_maxValue'){{/if}}{{#if min}}
        {{arrayIndent}}.min({{min}}, '{{labelName}}_min'){{/if}}{{#if max}}
        {{arrayIndent}}.max({{max}}, '{{labelName}}_max'){{/if}}{{#if regex}}
        {{arrayIndent}}.matches({{{regexValue}}}, '{{labelName}}_regex'){{/if}}
        {{arrayIndent}}.typeError('{{labelName}}_invalid'){{#if typeIsArray}})
        .typeError('{{labelName}}_invalid'){{/if}}{{/if}}{{#if required}}
        .required('{{labelName}}_required'){{else}}
        .notRequired(){{/if}}{{#if default}}
        .default({{{defaultValue}}}){{/if}}{{#if test}}
        .test({
            name: "{{test.message}}",
            message: '{{labelName}}_{{test.message}}',
            skipAbsent: true,
            test(value{{#if ../typescript}}: string | number | boolean | null | undefined{{/if}}, ctx) {
                const t = {{{testCode}}};
                return typeof value === "undefined" || value == null || t({ ...ctx.parent });
            }
        }){{/if}}{{#if hasWhen}}
        .when([{{{whenFieldNamesQuoted}}}], {
            is: ({{#if ../typescript}}{{whenFieldSignature}}{{else}}{{whenFieldNames}}{{/if}}) => {
                const w = {{{whenCode}}};
                const v{{#if ../typescript}}: Record<string, unknown>{{/if}} = { {{whenFieldNames}} };
                return w(v);
            },
            then: (schema) => schema.required('{{labelName}}_required'),
            otherwise: (schema) => schema.notRequired(),
        }){{/if}},{{/each}}
};

export const {{Name}}Schema = yup.object({{Name}}SchemaFields);
