import { apiRequest } from '@/shared/api/httpClient';
import { CurrentUser, SignInRequest } from '@/shared/types/auth';

export async function signIn(request: SignInRequest): Promise<CurrentUser> {
  return apiRequest<CurrentUser>('/auth/signin/local', {
    method: 'POST',
    body: {
      email: request.email,
      password: request.password,
    },
  });
}

export async function getCurrentUser(): Promise<CurrentUser> {
  return apiRequest<CurrentUser>('/auth/me');
}

export interface UpdateOwnProfileRequest {
  readonly name_prefix?: string | null;
  readonly firstName?: string;
  readonly lastName?: string;
  readonly phoneNumber?: string | null;
  readonly email?: string;
  /** Avatar file private URL from the upload, or null to clear. */
  readonly avatar?: string | null;
}

export async function updateOwnProfile(
  data: UpdateOwnProfileRequest,
): Promise<CurrentUser> {
  return apiRequest<CurrentUser>('/auth/me', {
    method: 'PUT',
    body: { data },
  });
}

export async function changePassword(
  currentPassword: string,
  newPassword: string,
): Promise<void> {
  await apiRequest<void>('/auth/password-update', {
    method: 'PUT',
    body: { currentPassword, newPassword },
  });
}

export async function refreshSession(): Promise<CurrentUser> {
  return apiRequest<CurrentUser>('/auth/refresh', {
    method: 'POST',
    skipAuthRefresh: true,
  });
}

export async function signOut(): Promise<void> {
  await apiRequest<void>('/auth/signout', {
    method: 'POST',
  });
}
