import Cookies from "js-cookie";
import { API_ACCESS_TOKEN_COOKIE_NAME, API_REFRESH_TOKEN_COOKIE_NAME } from "./constants.js";
import { API, api, inferOutput } from "astro-typesafe-api/client";

export async function loginClient(email: string, passwort: string): Promise<inferOutput<API["auth"]["refresh-token"]["GET"]> | null> {
	try {
		const response = await api.auth["refresh-token"].GET.fetch({
			email,
			passwort
		})
		
		const options = {
			domain: `.${window.location.hostname}`,
			path: "/",
			expires: response.exp
		}
		Cookies.set(API_ACCESS_TOKEN_COOKIE_NAME, response.accessToken, options);
		Cookies.set(API_REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, options);
		Cookies.set("uid", response.uid, options);
		
		return response;
	} catch (e) {
		return null;
		
	}
}