import { boot } from 'quasar/wrappers';
import { Client, Account, Databases, ID } from 'appwrite';
import { useAuthStore } from 'src/stores/auth';
import { Dialog, Notify } from 'quasar';
import type { Router } from 'vue-router';

const client = new Client();

// appwrite.io SaaS
// client
//   .setEndpoint('https://api.bab.toal.ca/v1')
//   .setProject('653ef6f76baf06d68034');
// const appDatabaseId = '654ac5044d1c446feb71';

// Private self-hosted appwrite
client
  .setEndpoint('https://apidev.bab.toal.ca/v1')
  .setProject('655a7116479b4d5a815f');
//TODO
const appDatabaseId = '';

const account = new Account(client);
const databases = new Databases(client);
let appRouter: Router;

export default boot(async ({ router }) => {
  // Initialize store
  const authStore = useAuthStore();
  await authStore.init();
  appRouter = router;
});

async function logout() {
  Dialog.create({
    title: 'Logout',
    message: 'Are you sure?',
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    const authStore = useAuthStore();
    await authStore.logout();
    Notify.create({
      message: 'Logged out!',
      type: 'warning',
      position: 'top',
      timeout: 2000,
      group: false,
    });
    appRouter.replace({ name: 'login' });
  });
}

function login(email: string, password: string) {
  const notification = Notify.create({
    type: 'primary',
    position: 'top',
    spinner: true,
    message: 'Logging you in...',
    timeout: 8000,
    group: false,
  });
  const authStore = useAuthStore();
  authStore
    .login(email, password)
    .then(() => {
      notification({
        type: 'positive',
        message: 'Logged in!',
        timeout: 2000,
        spinner: false,
        icon: 'check_circle',
      });
      console.log('Redirecting to index page');
      appRouter.replace({ name: 'index' });
    })
    .catch(function (reason: Error) {
      notification({
        type: 'negative',
        message: 'Login failed.',
        timeout: 1,
      });
      Dialog.create({
        title: 'Login Error!',
        message: reason.message,
        persistent: true,
      });
    });
}
export { client, account, databases, ID, appDatabaseId, login, logout };
