import { boot } from 'quasar/wrappers';
import {
  Client,
  Account,
  Databases,
  Functions,
  ID,
  AppwriteException,
  Teams,
} 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
if (process.env.APPWRITE_API_ENDPOINT && process.env.APPWRITE_API_PROJECT)
  client
    .setEndpoint(process.env.APPWRITE_API_ENDPOINT)
    .setProject(process.env.APPWRITE_API_PROJECT);
else if (process.env.DEV) {
  client
    .setEndpoint('http://localhost:4000/api/v1')
    .setProject('65ede55a213134f2b688');
} else {
  client.setEndpoint('https://appwrite.oys.undock.ca/v1').setProject('bab');
}
//TODO move this to config file
const AppwriteIds = process.env.DEV
  ? {
      databaseId: '65ee1cbf9c2493faf15f',
      collection: {
        boat: '66341910003e287cd71c',
        reservation: '663f8847000b8f5e29bb',
        skillTags: '66072582a74d94a4bd01',
        task: '65ee1cd5b550023fae4f',
        taskTags: '65ee21d72d5c8007c34c',
        interval: '66361869002883fb4c4b',
        intervalTemplate: '66361f480007fdd639af',
      },
      function: {
        userinfo: 'userinfo',
      },
    }
  : {
      databaseId: 'bab_prod',
      collection: {
        boat: 'boat',
        reservation: 'reservation',
        skillTags: 'skillTags',
        task: 'task',
        taskTags: 'taskTags',
        interval: 'interval',
        intervalTemplate: 'intervalTemplate',
      },
      function: {
        userinfo: '664038294b5473ef0c8d',
      },
    };

const account = new Account(client);
const databases = new Databases(client);
const functions = new Functions(client);
const teams = new Teams(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' });
  });
}

async 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();
  try {
    await authStore.login(email, password);
    notification({
      type: 'positive',
      message: 'Logged in!',
      timeout: 2000,
      spinner: false,
      icon: 'check_circle',
    });
    console.log('Redirecting to index page');
    appRouter.replace({ name: 'index' });
  } catch (error: unknown) {
    notification({
      type: 'negative',
      message: 'Login failed.',
      timeout: 2000,
    });
    if (error instanceof AppwriteException) {
      Dialog.create({
        title: 'Login Error!',
        message: error.message,
        persistent: true,
      });
    }
  }
}
export {
  client,
  account,
  teams,
  databases,
  functions,
  ID,
  AppwriteIds,
  login,
  logout,
};
