import { create } from 'zustand';
import { authService as tokenService } from '@/core/auth/auth.service';
import { authApi } from './auth.api';
import type { AuthUser } from '@/core/auth/auth.types';

interface AuthState {
  currentUser: AuthUser | null;
  loading: boolean;
  unreadCount: number;
  login: (email: string, password: string) => Promise<void>;
  fetchMe: () => Promise<void>;
  logout: () => void;
  reset: () => void;
}

function mapUser(u: Record<string, unknown>): AuthUser {
  return {
    id: u.id as number,
    email: u.email as string,
    fullName: (u.full_name ?? u.fullName ?? '') as string,
    roles: Array.isArray(u.roles) && u.roles.length ? u.roles : (u.is_admin ? ['SA'] : ['USER']),
    departmentId: (u.department_id ?? u.departmentId) as number | undefined,
  };
}

export const useAuthStore = create<AuthState>((set) => ({
  currentUser: null,
  loading: false,
  unreadCount: 0,

  login: async (email, password) => {
    set({ loading: 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);
      set({ currentUser: mapUser(data.user as unknown as Record<string, unknown>) });
    } finally {
      set({ loading: false });
    }
  },

  fetchMe: async () => {
    try {
      const { data } = await authApi.me();
      set({ currentUser: mapUser(data as unknown as Record<string, unknown>) });
    } catch {
      tokenService.clearTokens();
      set({ currentUser: null });
      window.location.href = '/login';
    }
  },

  logout: () => {
    tokenService.clearTokens();
    set({ currentUser: null });
    window.location.href = '/login';
  },

  reset: () => {
    set({ currentUser: null, loading: false, unreadCount: 0 });
  },
}));
