import { createContext } from 'preact';
import { useContext } from 'preact/hooks';
import type { Me, AccessLevel } from './types';

// Default identity used before /api/v1/me resolves (or if it fails): assume a
// trusted LAN user with full access, matching the backend default.
export const DEFAULT_ME: Me = { user: '', level: 'write', groups: [], canEditLogic: true, canViewAudit: true, canAdmin: true, defaultZoom: 1 };

// AuthContext carries the resolved identity + global access level for the
// current user throughout the app.
export const AuthContext = createContext<Me>(DEFAULT_ME);

export function useAuth(): Me {
  return useContext(AuthContext);
}

// canWrite reports whether the given level permits creating/modifying panels
// and writing signal values.
export function canWrite(level: AccessLevel): boolean {
  return level === 'write';
}

// canRead reports whether the given level permits viewing panels at all.
export function canRead(level: AccessLevel): boolean {
  return level !== 'none';
}

// fetchMe loads the caller's identity from the backend. On failure it falls
// back to the trusted-LAN default so the UI stays usable in dev/unproxied mode.
export async function fetchMe(): Promise<Me> {
  try {
    const res = await fetch('/api/v1/me');
    if (!res.ok) return DEFAULT_ME;
    const data = await res.json();
    return {
      user: typeof data.user === 'string' ? data.user : '',
      level: (data.level as AccessLevel) ?? 'write',
      groups: Array.isArray(data.groups) ? data.groups : [],
      canEditLogic: data.canEditLogic !== false,
      canViewAudit: data.canViewAudit !== false,
      canAdmin: data.canAdmin !== false,
      defaultZoom: typeof data.defaultZoom === 'number' && data.defaultZoom > 0 ? data.defaultZoom : 1,
    };
  } catch {
    return DEFAULT_ME;
  }
}
