import { create } from 'zustand'
import { getCookie, removeCookie, setCookie } from '@/lib/cookies'

const AUTH_SESSION = 'email_unlimit_admin_session'

export interface AuthUser {
  id: string
  email: string
  role: string
  status: string
}

interface StoredSession {
  user: AuthUser | null
  accessToken: string
  refreshToken: string
}

interface AuthState {
  auth: StoredSession & {
    setSession: (
      user: AuthUser,
      accessToken: string,
      refreshToken: string
    ) => void
    setTokens: (accessToken: string, refreshToken: string) => void
    reset: () => void
  }
}

function readSession(): StoredSession {
  const raw = getCookie(AUTH_SESSION)
  if (!raw) {
    return { user: null, accessToken: '', refreshToken: '' }
  }

  try {
    const value = JSON.parse(decodeURIComponent(raw)) as Partial<StoredSession>
    return {
      user: value.user ?? null,
      accessToken: value.accessToken ?? '',
      refreshToken: value.refreshToken ?? '',
    }
  } catch {
    removeCookie(AUTH_SESSION)
    return { user: null, accessToken: '', refreshToken: '' }
  }
}

function persistSession(session: StoredSession) {
  setCookie(AUTH_SESSION, encodeURIComponent(JSON.stringify(session)))
}

export const useAuthStore = create<AuthState>()((set) => {
  const initial = readSession()

  return {
    auth: {
      ...initial,
      setSession: (user, accessToken, refreshToken) =>
        set((state) => {
          const session = { user, accessToken, refreshToken }
          persistSession(session)
          return { ...state, auth: { ...state.auth, ...session } }
        }),
      setTokens: (accessToken, refreshToken) =>
        set((state) => {
          const session = { ...state.auth, accessToken, refreshToken }
          persistSession({
            user: session.user,
            accessToken,
            refreshToken,
          })
          return { ...state, auth: session }
        }),
      reset: () =>
        set((state) => {
          removeCookie(AUTH_SESSION)
          return {
            ...state,
            auth: {
              ...state.auth,
              user: null,
              accessToken: '',
              refreshToken: '',
            },
          }
        }),
    },
  }
})
