import { writable } from 'svelte/store';
import { api, setAccessToken } from '$lib/api';
import { EID_CHAT_STORAGE_KEY } from '$lib/eidChat';

interface User {
  id: number;
  username: string;
  is_active: boolean;
  totp_enabled: boolean;
  last_login_at: string | null;
}

export const user = writable<User | null>(null);
export const isAuthenticated = writable(false);

export async function login(username: string, password: string, totp_code?: string) {
  const data = await api<{ access_token: string }>('/auth/login', {
    method: 'POST',
    body: JSON.stringify({ username, password, totp_code: totp_code || undefined }),
  });
  setAccessToken(data.access_token);
  await fetchUser();
}

export async function fetchUser() {
  try {
    const data = await api<User>('/auth/me');
    user.set(data);
    isAuthenticated.set(true);
  } catch {
    user.set(null);
    isAuthenticated.set(false);
  }
}

export async function logout() {
  try {
    await api('/auth/logout', { method: 'POST' });
  } catch { /* ignore */ }
  setAccessToken(null);
  user.set(null);
  isAuthenticated.set(false);
  // 본문 무로깅 posture 정합 — 로그아웃 시 이드 대화 이력도 브라우저에서 제거
  if (typeof window !== 'undefined') {
    try {
      window.localStorage.removeItem(EID_CHAT_STORAGE_KEY);
    } catch {
      // 이력 제거 실패가 logout 자체를 막지는 않음
    }
  }
}

export async function tryRefresh() {
  try {
    const data = await api<{ access_token: string }>('/auth/refresh', {
      method: 'POST',
    });
    setAccessToken(data.access_token);
    await fetchUser();
    return true;
  } catch {
    return false;
  }
}
