import { create } from 'zustand'
import { persist } from 'zustand/middleware'

/**
 * Trakt.tv connection state. Tokens persist via Zustand's localStorage
 * adapter - they're per-device and not strictly "sensitive" in the same
 * way the Jellyfin server token is, since they can be revoked on
 * trakt.tv at any time.
 *
 * If you bundled client credentials at build time (env vars), they
 * override anything stored here.
 */

export interface TraktTokens {
  accessToken: string
  refreshToken: string
  expiresAt: string
}

interface State {
  /** OAuth client id - required for all calls. Get one from trakt.tv. */
  clientId: string
  clientSecret: string
  tokens: TraktTokens | null
  enabled: boolean
  setCredentials: (clientId: string, clientSecret: string) => void
  setTokens: (tokens: TraktTokens | null) => void
  setEnabled: (on: boolean) => void
  disconnect: () => void
}

export const useTrakt = create<State>()(
  persist(
    set => ({
      clientId: '',
      clientSecret: '',
      tokens: null,
      enabled: true,
      setCredentials: (clientId, clientSecret) => set({ clientId, clientSecret }),
      setTokens: tokens => set({ tokens }),
      setEnabled: enabled => set({ enabled }),
      disconnect: () => set({ tokens: null }),
    }),
    { name: 'trakt-v1' },
  ),
)

export function getTraktClientId(): string {
  const env = (import.meta.env.VITE_TRAKT_CLIENT_ID || '').trim()
  return env || useTrakt.getState().clientId
}

export function getTraktClientSecret(): string {
  const env = (import.meta.env.VITE_TRAKT_CLIENT_SECRET || '').trim()
  return env || useTrakt.getState().clientSecret
}
