import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', () => {
  const accessToken = useCookie('access_token', {
        sameSite: 'strict',
        secure: process.env.NODE_ENV === 'production',
        maxAge: 60 * 60 * 24,
    });
  const refreshToken = useCookie('refresh_token', {
        sameSite: 'strict',
        secure: process.env.NODE_ENV === 'production',
        maxAge: 60 * 60 * 24,
    });
  const user = ref<any>(null);

  const config = useRuntimeConfig();

  const login = async (username: string, password: string) => {
    try {
      const data = await $fetch(`${config.public.apiBase}/oauth/token/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          grant_type: 'password',
          client_id: config.public.clientId,
          client_secret: config.public.clientSecret,
          username,
          password,
        }).toString(),
      })

      accessToken.value = data.access_token;
      refreshToken.value = data.refresh_token;

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

  const fetchUser = async () => {
    if (!accessToken.value) return
    try {
      const data = await $fetch(`${config.public.apiBase}/auth/users/me/`, {
        headers: {
          Authorization: `Bearer ${accessToken.value}`,
        },
      })
      console.log('Fetched user:', data);
      user.value = data;
      return data;
    } catch (err) {
      await logout();
    }
  }

  const logout = async () => {
    if (!accessToken.value) return;

    try {
        const response = await $fetch(`${config.public.apiBase}/oauth/revoke_token/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                client_id: config.public.clientId,
                client_secret: config.public.clientSecret,
                token: accessToken.value,
            }).toString(),
        });
    } catch (err) {
        console.error('Logging out failed:', err);
    }

    accessToken.value = null;
    refreshToken.value = null;
    user.value = null;
  };

  const refresh = async () => {
    try {
      const data = await $fetch(`${config.public.apiBase}/oauth/token/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          grant_type: 'refresh_token',
          client_id: config.public.clientId,
          client_secret: config.public.clientSecret,
          refresh_token: `${refreshToken.value}`,
        }).toString(),
      })

      accessToken.value = data.access_token;
      refreshToken.value = data.refresh_token;

      return true;
    } catch (error: any) {
      console.error('Refresh token failed', error)
      throw error
    }
  }

  return {
    user,
    accessToken,
    login,
    logout,
    fetchUser,
    refresh,
  }
})
