import { api, setToken, clearToken } 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>("/login", { ...data, email: data.login });
    setToken(res.token);
    return res;
  },

  async logout(): Promise<void> {
    await api.post<void>("/logout").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);
  },
};
