/**
 * 로그인 세션 (localStorage).
 * - 미로그인: X-Device-Id 만 전송 → 기존과 동일 (기기별 설정)
 * - 로그인: X-User-Id 전송 → 사용자별 DB 설정 공유
 */

import type { UserRole } from './permissions';
import { normalizeRole } from './permissions';

export interface AuthSession {
  userId: number;
  username: string;
  displayName: string;
  role: UserRole;
}

const USER_ID_KEY = 'gc_user_id';
const USERNAME_KEY = 'gc_username';
const DISPLAY_NAME_KEY = 'gc_display_name';
const ROLE_KEY = 'gc_user_role';

export function getAuthSession(): AuthSession | null {
  const id = localStorage.getItem(USER_ID_KEY);
  if (!id) return null;
  const userId = Number(id);
  if (!Number.isFinite(userId) || userId <= 0) return null;
  const username = localStorage.getItem(USERNAME_KEY) ?? '';
  const displayName = localStorage.getItem(DISPLAY_NAME_KEY) ?? username;
  const storedRole = localStorage.getItem(ROLE_KEY);
  const role = normalizeRole(storedRole ?? 'USER');
  return { userId, username, displayName, role };
}

export function setAuthSession(session: AuthSession): void {
  localStorage.setItem(USER_ID_KEY, String(session.userId));
  localStorage.setItem(USERNAME_KEY, session.username);
  localStorage.setItem(DISPLAY_NAME_KEY, session.displayName);
  localStorage.setItem(ROLE_KEY, session.role);
}

export function clearAuthSession(): void {
  localStorage.removeItem(USER_ID_KEY);
  localStorage.removeItem(USERNAME_KEY);
  localStorage.removeItem(DISPLAY_NAME_KEY);
  localStorage.removeItem(ROLE_KEY);
}

export function isLoggedIn(): boolean {
  return getAuthSession() !== null;
}
