import { api } from '@/core/services/api'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import type {
  ForgotPasswordPayload,
  ForgotPasswordResponse,
  LoginCredentials,
  LoginResponse,
  LoginVerificationRequiredData,
  RegisterCredentials,
  RegisterResponse,
  ResendVerificationResponse,
  ResetPasswordPayload,
  ResetPasswordResponse,
  SessionResponse,
  SwitchRoleResponse,
  VerifyEmailPayload,
  VerifyEmailResponse,
} from '../types/auth.types'

export async function login(credentials: LoginCredentials): Promise<LoginResponse> {
  const { data } = await api.post<LoginResponse>('/login', credentials)
  return data
}

export async function register(credentials: RegisterCredentials): Promise<RegisterResponse> {
  const { data } = await api.post<RegisterResponse>('/register', credentials)
  return data
}

export async function verifyEmail(payload: VerifyEmailPayload): Promise<VerifyEmailResponse> {
  const { data } = await api.post<VerifyEmailResponse>('/verify-email', payload)
  return data
}

export async function resendVerificationEmail(email: string): Promise<ResendVerificationResponse> {
  const { data } = await api.post<ResendVerificationResponse>('/verify-email/resend', { email })
  return data
}

export async function requestForgotPassword(
  payload: ForgotPasswordPayload,
): Promise<ForgotPasswordResponse> {
  const { data } = await api.post<ForgotPasswordResponse>('/forgot-password', payload)
  return data
}

export async function resetPassword(
  payload: ResetPasswordPayload,
): Promise<ResetPasswordResponse> {
  const { data } = await api.post<ResetPasswordResponse>('/reset-password', payload)
  return data
}

export async function fetchCurrentUser(): Promise<SessionResponse> {
  const { data } = await api.get<SessionResponse>('/v1/me')
  return data
}

export async function switchActiveRole(roleId: string): Promise<SwitchRoleResponse> {
  const { data } = await api.post<SwitchRoleResponse>('/v1/active-role/switch', { role_id: roleId })
  return data
}

export async function logout(): Promise<void> {
  await api.post('/v1/logout')
}

export function getAuthErrorMessage(error: unknown): string {
  return getApiErrorMessage(error, 'Login failed. Please try again.')
}

export function getRegisterErrorMessage(error: unknown): string {
  return getApiErrorMessage(error, 'Registration failed. Please try again.')
}

export function getVerifyEmailErrorMessage(error: unknown): string {
  return getApiErrorMessage(error, 'Email verification failed. Please try again.')
}

export function getForgotPasswordErrorMessage(error: unknown): string {
  return getApiErrorMessage(error, 'Gagal menghantar kod OTP. Sila cuba lagi.')
}

export function getResetPasswordErrorMessage(error: unknown): string {
  return getApiErrorMessage(error, 'Gagal menetapkan semula kata laluan. Sila cuba lagi.')
}

export function isAccountPending(user: { status: string } | null | undefined): boolean {
  return user?.status === 'pending'
}

export function isLoginVerificationRequired(
  response: LoginResponse,
): response is LoginResponse & { data: LoginVerificationRequiredData } {
  return 'requires_email_verification' in response.data
    && response.data.requires_email_verification === true
}

export function resolvePostAuthRoute(
  user: { status: string } | null | undefined,
  redirectPath?: string,
) {
  if (isAccountPending(user)) {
    return { name: 'account-pending' }
  }

  const routes: Record<string, { name: string }> = {
    '/profile': { name: 'profile-overview-2' },
  }

  return routes[redirectPath ?? ''] ?? { name: 'profile-overview-2' }
}

export function resolvePostLoginRoute(redirectPath: string, user?: { status: string } | null) {
  return resolvePostAuthRoute(user, redirectPath)
}
