import { api, type User, type LoginResponse } from '$lib/api/client';
import { queryClient } from '$lib/query/client';
import { clearPersistedQueue } from '$lib/player/persisted';
import { playQueue, closeQueueDrawer } from '$lib/player/store.svelte';

let _user = $state<User | null>(null);

export const user = {
  get value(): User | null {
    return _user;
  }
};

export async function bootstrap(): Promise<void> {
  try {
    _user = await api.get<User>('/api/me');
  } catch {
    _user = null;
  }
}

export async function login(username: string, password: string): Promise<void> {
  const res = await api.post<LoginResponse>('/api/auth/login', { username, password });
  _user = res.user;
}

export async function logout(opts: { silent?: boolean } = {}): Promise<void> {
  const userId = _user?.id;
  if (!opts.silent) {
    try {
      await api.post('/api/auth/logout', {});
    } catch {
      // best effort — server-side session may already be gone
    }
  }
  _user = null;
  queryClient.clear();
  // M7 #364: clear queue persistence + reset in-memory queue + close drawer
  // so a subsequent login doesn't inherit the previous user's playback state.
  if (userId) clearPersistedQueue(userId);
  playQueue([]);
  closeQueueDrawer();
}
