import { combine, createDomain, sample } from 'effector';
import { createGate } from 'effector-react';
import { Project, ProjectsList, RouteGenerateResC, RouteGenerateRes } from '../../bff-auth/src/export-types';

const generateDomain = createDomain('generate');
export const ProjectsGate = createGate();

export const getProjectsFx = generateDomain.effect(
    async (): Promise<Array<Project>> => {
        const res = await fetch(
            "http://localhost:3000/get-projects",
            {
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                },
                mode: "cors",
            });

        const reJsonedData: unknown = await res.json();

        const checkedData = ProjectsList.parse(reJsonedData);
        
        return checkedData;
    }
);

export const generateFx = generateDomain.effect(
    async (
        req: {
            document_type: string;
            project: string;
            page_name: string; 
            jira_text: string; 
            attached_link: string; 
        }
    ): Promise<RouteGenerateRes> => {
        const res = await fetch(
            "http://localhost:3000/generate",
            {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(req),
                mode: "cors",
            }
        );
        const reJsonedData: unknown = await res.json();

        const checkedData = RouteGenerateResC.parse(reJsonedData);
        
        return checkedData;
    }
);

export const retryClicked = generateDomain.event();
export const resetError = generateDomain.event();

export const $projects = generateDomain.store<Array<Project>>([])
    .on(getProjectsFx.doneData, (_, payload) => payload);
export const $loaded = generateDomain.store<boolean>(false)
    .on(getProjectsFx.done, () => true);
export const $error = generateDomain.store<string | null>(null)
    .on(getProjectsFx.failData, (_, err) => {
        console.log('>>>', err)
        // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
        return err?.message ?? 'Неизвестная ошибка'
    })
    .on(getProjectsFx.done, () => null)
    .on(resetError, () => null);

export const $pending = getProjectsFx.pending;
const $canAutoLoad = combine(
    $loaded,
    $pending,
    (loaded, pending) => !loaded && !pending
);

sample({
    clock: ProjectsGate.open,
    filter: $canAutoLoad,
    target: [resetError, getProjectsFx]
});

sample({
    clock: retryClicked,
    source: $pending,
    filter: (pending) => !pending,
    target: [resetError, getProjectsFx],
});
