import { appApi } from 'src/boot/axios';
import { useUserStore } from './userStore';
import { useNotify } from '../general/useNotify';
import type { Settings } from '../models/settings';
import { Logo } from '../models/logo';

const refreshTime = 10000;
let intervalId: ReturnType<typeof setInterval> | null = null;

export function useLogin() {
  const userStore = useUserStore();
  const { NotifyResponse } = useNotify();

  async function login(user: string, password: string) {
    try {
      await appApi.post('/login', { user, password }).then((resp) => {
        const sets = resp.data.settings as Settings;

        Logo.value = sets.icon;
        document.documentElement.style.setProperty('--q-primary', sets.primaryColor);
        document.documentElement.style.setProperty('--q-secondary', sets.secondaryColor);
        localStorage.setItem('icon', sets.icon);
        localStorage.setItem('databaseName', sets.databaseName);
        localStorage.setItem('primaryColor', sets.primaryColor);
        localStorage.setItem('secondaryColor', sets.secondaryColor);
      });

      const resp = await appApi.get('/login/me');
      userStore.setUser({ id: resp.data.id, username: resp.data.user, role: resp.data.role });

      startRefreshInterval();
      return true;
    } catch (err) {
      console.error('Login error:', err);
      throw err;
    }
  }

  async function logout() {
    await appApi.get('/logout').catch((err) => {
      NotifyResponse(err, 'error');
    });

    userStore.clearUser();
    stopRefreshInterval();
  }

  async function refresh() {
    await appApi
      .post('secure/login/refresh', {}, { withCredentials: true })
      .then(() => {
        appApi
          .get('/login/me')
          .then((resp) => {
            userStore.setUser({ id: resp.data.id, username: resp.data.user, role: resp.data.role });
            if (!intervalId) {
              startRefreshInterval();
            }
            return true;
          })
          .catch(() => {});
      })
      .catch(() => {
        userStore.clearUser();
      });
    stopRefreshInterval();
    return false;
  }
  function getUser() {
    return userStore.getUser();
  }

  function startRefreshInterval() {
    intervalId = setInterval(() => {
      refresh().catch((err) => NotifyResponse(err, 'error'));
    }, refreshTime);
  }
  function stopRefreshInterval() {
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
  }

  return { login, logout, refresh, getUser };
}
