import cookie from 'cookie'
import { useAuthStore } from '~/stores/auth'

export default defineNuxtPlugin(() => {
  const auth = useAuthStore()

  try {
    const cookies = cookie.parse(useRequestHeaders().cookie || '')
    const authCookie = cookies['authentication-cookie']

    if (authCookie) {
      const parsed = JSON.parse(authCookie)
      auth.setPayload(parsed.auth)
    }
  } catch (err) {
    console.error('Failed to parse authentication cookie', err)
  }
})
