import {
    DocumentsType,
    DocumentVariantsValue,
    IAdditionalFields,
    IApiResponse,
    IPassportValue,
    IPatentForm,
    IPatentValue,
    TAvailableDoc,
} from '@/modules/documents';

interface IPrepareData {
    value: any;
    addition_fields?: IAdditionalFields;
}

export default function () {
    const preparePatentForServer = (data: IPatentForm): IPrepareData => {
        const { document, blank, ...rest } = data;
        return {
            value: {
                ...rest,
                seria: document.substring(0, 2),
                number: document.substring(2),
                blank_seria: blank.substring(0, 2),
                blank_number: blank.substring(2),
            },
        };
    };

    const preparePassportForServer = (data: IPassportValue): IPrepareData => {
        const { region_id, ...value } = data;

        return {
            value,
            addition_fields: {
                region_id,
            },
        };
    };

    const preparePassportFromServer = (data: IPassportValue, doc?: IApiResponse) => {
        return {
            ...data,
            birth_date: window.$app.$formatters.formatServerDate(data?.birth_date),
            issue_date: window.$app.$formatters.formatServerDate(data?.issue_date),
            region_id: (doc?.addition_fields as IAdditionalFields)?.region_id,
        };
    };

    const preparePatentFromServer = (data: IPatentValue): IPatentForm => {
        return {
            document: `${data.seria}${data.number}`,
            blank: `${data.blank_seria ?? ''}${data.blank_number ?? ''}`,
            issue_date: window.$app.$formatters.formatServerDate(data.issue_date),
            paid_until: window.$app.$formatters.formatServerDate(data.paid_until),
        };
    };

    const prepareDataForServerMap = {
        [DocumentsType.PATENT]: preparePatentForServer,
        [DocumentsType.NONRESIDENT_PASSPORT]: preparePassportForServer,
    } as const;

    const prepareFromServer = (
        type: DocumentVariantsValue,
        formData: TAvailableDoc,
        doc?: IApiResponse,
    ) => {
        // formData может быть как полным запросом (IApiRequest*), так и уже "value".
        const rawValue = (formData as any)?.value ?? formData;

        if (type === DocumentsType.NONRESIDENT_PASSPORT) {
            return preparePassportFromServer(rawValue as IPassportValue, doc);
        }

        if (type === DocumentsType.PATENT) {
            return preparePatentFromServer(rawValue as IPatentValue);
        }

        return formData;
    };

    const prepareForServer = (
        type: DocumentVariantsValue,
        formData: TAvailableDoc,
    ): IPrepareData => {
        if (!prepareDataForServerMap[type]) {
            return { value: formData };
        }

        return prepareDataForServerMap[type](formData);
    };

    return {
        prepareFromServer,
        prepareForServer,
    };
}
