import type { AuthResult } from '../api/auth'
import type { StoredAuth } from '../types/session'

const AUTH_STORAGE_KEY = 'mahjong_auth'

export function readStoredAuth(): StoredAuth | null {
  const raw = localStorage.getItem(AUTH_STORAGE_KEY)
  if (!raw) {
    return null
  }

  try {
    const parsed = JSON.parse(raw) as StoredAuth
    if (typeof parsed.token !== 'string' || parsed.token.length === 0) {
      return null
    }

    return parsed
  } catch {
    return null
  }
}

export function saveAuth(result: AuthResult): StoredAuth {
  const value: StoredAuth = {
    token: result.token,
    tokenType: result.tokenType,
    refreshToken: result.refreshToken,
    expiresIn: result.expiresIn,
    user: result.user,
  }

  localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(value))
  return value
}

export function clearAuth(): void {
  localStorage.removeItem(AUTH_STORAGE_KEY)
}

export function writeStoredAuth(value: StoredAuth): void {
  localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(value))
}
