/*
|--------------------------------------------------------------------------
| Preloaded File - node ace make:preload rules/dependentArrayMinLength
|--------------------------------------------------------------------------
|*/

import { FieldContext } from '@vinejs/vine/types';
import vine, { VineArray } from '@vinejs/vine';
import { SchemaTypes } from '@vinejs/vine/types';

/**
 * Options accepted by the dependentArrayMinLength rule
 */
type Options = {
    min: number;
    dependentArray: string;
};

async function dependentArrayMinLength(value: unknown, options: Options, field: FieldContext) {
    const fileInputs = field.data[options.dependentArray]; // Access the dependent array
    const isArrayValue = Array.isArray(value);
    const isArrayFileInputs = Array.isArray(fileInputs);

    if (isArrayValue && isArrayFileInputs) {
        if (value.length >= options.min) {
            return true; // Valid if the main array length meets the minimum
        } else if (value.length === 0 && fileInputs.length >= options.min) {
            return true; // Valid if the main array is empty and the dependent array meets the minimum
        } else {
            field.report(
                `At least {{ min }} item for {{field}} field must be defined`,
                'array.dependentArrayMinLength',
                field,
                options,
            );
        }
    } else {
        // Report if either value or dependentArray is not an array
        field.report(
            `Both the {{field}} field and dependent array {{dependentArray}} must be arrays.`,
            'array.dependentArrayMinLength',
            field,
            options,
        );
    }

    return false; // Invalid if none of the conditions are met
}

export const dependentArrayMinLengthRule = vine.createRule(dependentArrayMinLength);

// Extend the VineArray interface with the same type parameters
declare module '@vinejs/vine' {
    interface VineArray<Schema extends SchemaTypes> {
        dependentArrayMinLength(options: Options): this;
    }
}

VineArray.macro('dependentArrayMinLength', function <Schema extends SchemaTypes>(this: VineArray<Schema>, options: Options) {
    return this.use(dependentArrayMinLengthRule(options));
});
