import { defineStore } from 'pinia';
import { ref } from 'vue';
import { authService as tokenService } from '@/core/auth/auth.service';
import { authApi } from './auth.api';
import type { AuthUser } from '@/core/auth/auth.types';

export const useAuthStore = defineStore('auth', () => {
  const currentUser = ref<AuthUser | null>(null);
  const loading = ref(false);
  const unreadCount = ref(0);

  async function login(email: string, password: string) {
    loading.value = true;
    try {
      const { data } = await authApi.login({ email, password });
      const accessToken = (data.access_token ?? data.accessToken) as string;
      const refreshToken = (data.refresh_token ?? data.refreshToken) as string;
      tokenService.setTokens(accessToken, refreshToken);
      currentUser.value = mapUser(data.user);
    } finally {
      loading.value = false;
    }
  }

  function mapUser(u: any): AuthUser {
    return {
      id: u.id,
      email: u.email,
      fullName: u.full_name ?? u.fullName ?? '',
      roles: u.roles?.length ? u.roles : (u.is_admin ? ['SA'] : ['USER']),
      departmentId: u.department_id ?? u.departmentId,
    };
  }

  async function fetchMe() {
    try {
      const { data } = await authApi.me();
      currentUser.value = mapUser(data);
    } catch {
      logout();
    }
  }

  function logout() {
    tokenService.clearTokens();
    currentUser.value = null;
    window.location.href = '/login';
  }

  function $reset() {
    currentUser.value = null;
    loading.value = false;
    unreadCount.value = 0;
  }

  return { currentUser, loading, unreadCount, login, fetchMe, logout, $reset };
});
