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();

const API_ENDPOINT = import.meta.env.VITE_APPWRITE_API_ENDPOINT;
const API_PROJECT = import.meta.env.VITE_APPWRITE_API_PROJECT;

if (API_ENDPOINT && API_PROJECT) {
  client.setEndpoint(API_ENDPOINT).setProject(API_PROJECT);
} else {
  console.error(
    'Must configure VITE_APPWRITE_API_ENDPOINT and VITE_APPWRITE_API_PROJECT'
  );
}

type AppwriteIDConfig = {
  databaseId: string;
  collection: {
    boat: string;
    reservation: string;
    skillTags: string;
    task: string;
    taskTags: string;
    interval: string;
    intervalTemplate: string;
  };
  function: {
    userinfo: string;
  };
};

let AppwriteIds = <AppwriteIDConfig>{};

console.log(API_ENDPOINT);
if (
  API_ENDPOINT === 'https://apidev.bab.toal.ca/v1' ||
  API_ENDPOINT === 'http://localhost:4000/api/v1'
) {
  AppwriteIds = {
    databaseId: '65ee1cbf9c2493faf15f',
    collection: {
      boat: 'boat',
      reservation: 'reservation',
      skillTags: 'skillTags',
      task: 'task',
      taskTags: 'taskTags',
      interval: 'interval',
      intervalTemplate: 'intervalTemplate',
    },
    function: {
      userinfo: 'userinfo',
    },
  };
} else if (API_ENDPOINT === 'https://appwrite.oys.undock.ca/v1') {
  AppwriteIds = {
    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',
    });
    appRouter.replace({ name: 'index' });
  } catch (error: unknown) {
    console.log(error);
    if (error instanceof AppwriteException) {
      if (error.type === 'user_session_already_exists') {
        appRouter.replace({ name: 'index' });
        notification({
          type: 'positive',
          message: 'Already Logged in!',
          timeout: 2000,
          spinner: false,
          icon: 'check_circle',
        });
        return;
      }
      Dialog.create({
        title: 'Login Error!',
        message: error.message,
        persistent: true,
      });
    }
    notification({
      type: 'negative',
      message: 'Login failed.',
      timeout: 2000,
    });
  }
}

async function resetPassword(email: string) {
  await account.createRecovery(email, window.location.origin + '/pwreset');
}

export {
  client,
  account,
  teams,
  databases,
  functions,
  ID,
  AppwriteIds,
  login,
  logout,
  resetPassword,
};
