// Authentication endpoints. Mirrors the login/register/
// handleAuthAPICall trio in the Angular TripDataService, with the
// request body typed instead of assembled ad hoc.
import apiClient from './client';
import { AuthResponse } from '../models/auth-response';
import { User } from '../models/user';

interface AuthRequestBody {
  name: string;
  email: string;
  password: string;
}

async function handleAuthApiCall(
  endpoint: 'login' | 'register',
  user: User,
  password: string
): Promise<AuthResponse> {
  const body: AuthRequestBody = {
    name: user.name,
    email: user.email,
    password
  };
  const response = await apiClient.post<AuthResponse>(`/${endpoint}`, body);
  return response.data;
}

export function login(user: User, password: string): Promise<AuthResponse> {
  return handleAuthApiCall('login', user, password);
}

export function register(user: User, password: string): Promise<AuthResponse> {
  return handleAuthApiCall('register', user, password);
}
