import { api, setToken, clearToken, persistTokenBundle } from "@/lib/api-client";
import type { LoginRequest, LoginResponse, User, ResetPasswordRequest, CurrentUserResponse } from "@/types";
import type { ApiSuccessResponse } from "@/types";

export const authService = {
  async login(data: LoginRequest): Promise<LoginResponse> {
    // Odoo accepts `login` or `email` in JSON body
    const res = await api.post<LoginResponse & {
      access_token?: string;
      refresh_token?: string;
      expires_in?: number;
    }>("/login", { ...data, email: data.login });
    // Persist the full bundle so the transparent refresh loop in api-client
    // has everything it needs. Falls back to the legacy single-token field
    // for older backends that only return ``token``.
    if (res.access_token || res.refresh_token) {
      persistTokenBundle({
        access_token: res.access_token,
        token: res.token,
        refresh_token: res.refresh_token,
        expires_in: res.expires_in,
      });
    } else {
      setToken(res.token);
    }
    return res;
  },

  async logout(): Promise<void> {
    const refresh = localStorage.getItem("encoach_refresh_token") || undefined;
    await api
      .post<void>("/logout", refresh ? { refresh_token: refresh } : undefined)
      .catch(() => {});
    clearToken();
  },

  async getUser(): Promise<User> {
    const res = await api.get<CurrentUserResponse>("/user");
    return res.user;
  },

  async resetPassword(data: ResetPasswordRequest): Promise<ApiSuccessResponse> {
    return api.post<ApiSuccessResponse>("/reset/sendVerification", data);
  },

  async setInvitePassword(data: { token: string; password: string }): Promise<ApiSuccessResponse> {
    return api.post<ApiSuccessResponse>("/auth/invite/set-password", data);
  },
};
