import { beforeEach, describe, expect, it, vi } from 'vitest';

vi.mock('@/lib/auth/tokenManager', () => ({
  clearStoredSession: vi.fn(),
  getStoredSession: vi.fn(),
  setStoredSession: vi.fn(),
}));

vi.mock('@/lib/api/auth', () => ({
  getCurrentSession: vi.fn(),
  login: vi.fn(),
  logout: vi.fn(),
  register: vi.fn(),
}));

import { getStoredSession } from '@/lib/auth/tokenManager';
import { getCurrentSession } from '@/lib/api/auth';
import { useAuthStore } from './authStore';

describe('authStore', () => {
  beforeEach(() => {
    useAuthStore.setState({
      user: null,
      session: null,
      accessToken: null,
      refreshToken: null,
      expiresAt: null,
      isAuthenticated: false,
      isLoading: false,
      error: null,
      hasHydrated: false,
      status: 'idle',
    });
    vi.clearAllMocks();
  });

  it('hydrates from stored session and confirms with server session endpoint', async () => {
    (getStoredSession as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
      accessToken: 'access-token',
      refreshToken: 'refresh-token',
      expiresAt: 123456,
    });
    (getCurrentSession as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
      authenticated: true,
      user: {
        id: 'user-1',
        username: 'tester',
        email: 'tester@example.com',
        isActive: true,
        isSuperuser: true,
        permissions: ['*'],
        roles: ['admin'],
      },
      session: {
        id: 'session-1',
        status: 'active',
        current: true,
        createdAt: 1,
        updatedAt: 2,
        expiresAt: 3,
      },
    });

    useAuthStore.getState().hydrate();
    await Promise.resolve();

    const state = useAuthStore.getState();
    expect(getCurrentSession).toHaveBeenCalledTimes(1);
    expect(state.hasHydrated).toBe(true);
    expect(state.isAuthenticated).toBe(true);
    expect(state.status).toBe('authenticated');
    expect(state.user?.username).toBe('tester');
    expect(state.session?.id).toBe('session-1');
  });
});
