<template>
  <LoginView
    :company-name="companyProfile.name"
    :submitting="loginSubmitting"
    :error-message="loginError"
    @login="submitLogin"
    @recover-password="handleRecoverPassword"
    @sso-login="handleSsoLogin"
  />
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'

import { useSystemState } from '../composables/useSystemState.js'
import LoginView from './LoginView.vue'

const route = useRoute()
const router = useRouter()
const {
  companyProfile,
  handleLogin,
  handleRecoverPassword,
  handleSsoLogin,
  loginError,
  loginSubmitting,
  resolveEntryRoute
} = useSystemState()

async function submitLogin(credentials) {
  const passed = await handleLogin(credentials)

  if (!passed) {
    return
  }

  const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : ''

  if (redirect.startsWith('/app/')) {
    router.replace(redirect)
    return
  }

  router.replace(resolveEntryRoute())
}
</script>
