import { createDomain, sample } from 'effector';
import { LoginSession, LoginSessionC } from '../../bff-auth/src/export-types';
import { persist } from 'effector-storage';
import { authUtilsCookieEffectorStorageAdapter } from './auth-utils-cookies-effector-storage-adapter';

const authDomain = createDomain('auth');

export const sendLoginFromFx = authDomain.effect(
    async (values: { username: string; password: string; }): Promise<LoginSession | null> => {
        const res = await fetch("http://localhost:3000/login", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(values),
            credentials: "include",
            mode: "cors",
        });

        let data: LoginSession | null = null;
        try {
            data = LoginSessionC.parse(await res.json());

        } catch {
            if (!res.ok) {
                throw new Error(`Auth parse request failed: ${String(res.status)}`); // todo 
            }
        }
        console.log('>>>', data)
        return data;
    }
);

export const logoutPressed = authDomain.event();

export const $session = authDomain.store<null | LoginSession>(null)
    .on(sendLoginFromFx.done, (_, payload) => payload.result)
    .on(sendLoginFromFx.fail, () => null)
    .on(logoutPressed, () => null);

persist({
    store: $session,
    key: "session",
    adapter: authUtilsCookieEffectorStorageAdapter({ expiresDays: 7, sameSite: "lax" })
});


export const $isAuthenticated = authDomain.store<boolean>($session.getState() !== null) // ?
    .on($session, (_, session) => session !== null)




const showSuccessMessage = authDomain.event();
const showErrorMessage = authDomain.event();

sample({
    clock: sendLoginFromFx.doneData,
    target: showSuccessMessage,
});

sample({
    clock: sendLoginFromFx.failData,
    target: showErrorMessage,
});

