import { AppRouter } from "@ibcornelsen/api";
import { inferProcedureOutput } from "@trpc/server";
import Cookies from "js-cookie";
import { client } from "src/trpc"
import { API_ACCESS_TOKEN_COOKIE_NAME, API_REFRESH_TOKEN_COOKIE_NAME } from "./constants";

export async function loginClient(email: string, passwort: string): Promise<inferProcedureOutput<AppRouter["v1"]["benutzer"]["getRefreshToken"]> | null> {
	try {
		const response = await client.v1.benutzer.getRefreshToken.query({
			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;
		
	}
}