import { apiClient } from './client';
import type { LoginRequest, RegisterRequest, LoginResponse } from '@horux/shared';

export async function login(data: LoginRequest): Promise<LoginResponse> {
  const response = await apiClient.post<LoginResponse>('/auth/login', data);
  return response.data;
}

export async function register(data: RegisterRequest): Promise<LoginResponse> {
  const response = await apiClient.post<LoginResponse>('/auth/register', data);
  return response.data;
}

export async function logout(): Promise<void> {
  const refreshToken = localStorage.getItem('refreshToken');
  await apiClient.post('/auth/logout', { refreshToken });
}

export async function getMe(): Promise<LoginResponse['user']> {
  const response = await apiClient.get('/auth/me');
  return response.data.user;
}

export async function requestPasswordReset(email: string): Promise<{ message: string }> {
  const response = await apiClient.post('/auth/password-reset/request', { email });
  return response.data;
}

export async function confirmPasswordReset(token: string, newPassword: string): Promise<{ message: string }> {
  const response = await apiClient.post('/auth/password-reset/confirm', { token, newPassword });
  return response.data;
}

export async function changePassword(currentPassword: string, newPassword: string): Promise<{ message: string }> {
  const response = await apiClient.post('/auth/password-change', { currentPassword, newPassword });
  return response.data;
}

export async function logoutAll(): Promise<{ message: string }> {
  const response = await apiClient.post('/auth/logout-all');
  return response.data;
}

export async function switchTenant(tenantId: string): Promise<LoginResponse> {
  const refreshToken = localStorage.getItem('refreshToken') || '';
  const response = await apiClient.post<LoginResponse>('/auth/switch-tenant', { tenantId, refreshToken });
  return response.data;
}
