import { create } from 'zustand'

interface User {
  id: string
  email: string
  firstName: string
  lastName: string
  role: string
}

interface AuthState {
  token: string | null
  user: User | null
  permissions: Set<string>
  permissionsLoaded: boolean
  setAuth: (token: string, user: User) => void
  setPermissions: (slugs: string[]) => void
  hasPermission: (slug: string) => boolean
  logout: () => void
}

/**
 * Permission inheritance: admin implies edit implies view for the same domain.
 * Must match the backend logic in plugins/auth.ts.
 */
const ACTION_HIERARCHY: Record<string, string[]> = {
  admin: ['admin', 'edit', 'view'],
  edit: ['edit', 'view'],
  view: ['view'],
  upload: ['upload'],
  delete: ['delete'],
  send: ['send'],
  export: ['export'],
}

function expandPermissions(slugs: string[]): Set<string> {
  const expanded = new Set<string>()
  for (const slug of slugs) {
    expanded.add(slug)
    const [domain, action] = slug.split('.')
    const implied = ACTION_HIERARCHY[action]
    if (implied && domain) {
      for (const a of implied) {
        expanded.add(`${domain}.${a}`)
      }
    }
  }
  return expanded
}

function loadSession(): { token: string; user: User; permissions?: string[] } | null {
  try {
    const raw = sessionStorage.getItem('lunarfront-auth')
    if (!raw) return null
    return JSON.parse(raw)
  } catch {
    return null
  }
}

function saveSession(token: string, user: User, permissions?: string[]) {
  sessionStorage.setItem('lunarfront-auth', JSON.stringify({ token, user, permissions }))
}

function clearSession() {
  sessionStorage.removeItem('lunarfront-auth')
}

export const useAuthStore = create<AuthState>((set, get) => {
  const initial = typeof window !== 'undefined' ? loadSession() : null
  const initialPerms = initial?.permissions ? expandPermissions(initial.permissions) : new Set<string>()
  return {
  token: initial?.token ?? null,
  user: initial?.user ?? null,
  permissions: initialPerms,
  permissionsLoaded: initialPerms.size > 0,

  setAuth: (token, user) => {
    saveSession(token, user)
    set({ token, user })
  },

  setPermissions: (slugs: string[]) => {
    const expanded = expandPermissions(slugs)
    const { token, user } = get()
    if (token && user) {
      saveSession(token, user, slugs)
    }
    set({ permissions: expanded, permissionsLoaded: true })
  },

  hasPermission: (slug: string) => {
    return get().permissions.has(slug)
  },

  logout: () => {
    clearSession()
    set({ token: null, user: null, permissions: new Set(), permissionsLoaded: false })
  },
}})
