export const useCookie = () => {
  function getCookie(name: string): string | null {
    const cookies = document.cookie ? document.cookie.split('; ') : []

    for (const cookie of cookies) {
      const [key, ...rest] = cookie.split('=')
      if (key === name) {
        return decodeURIComponent(rest.join('='))
      }
    }
    
    return null
  }

  function setCookie(
    name: string,
    value: string,
    options?: {
      days?: number
      path?: string
      domain?: string
      secure?: boolean
      sameSite?: 'Lax' | 'Strict' | 'None'
    },
  ) {
    let cookie = `${name}=${encodeURIComponent(value)}`

    if (options?.days) {
      const date = new Date()
      date.setTime(date.getTime() + options.days * 24 * 60 * 60 * 1000)
      cookie += `; expires=${date.toUTCString()}`
    }

    cookie += `; path=${options?.path ?? '/'}`

    if (options?.domain) {
      cookie += `; domain=${options.domain}`
    }

    if (options?.secure) {
      cookie += `; Secure`
    }

    if (options?.sameSite) {
      cookie += `; SameSite=${options.sameSite}`
    }

    document.cookie = cookie
  }

  function deleteCookie(name: string, path: string = '/', domain?: string) {
    let cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}`

    if (domain) {
      cookie += `; domain=${domain}`
    }

    document.cookie = cookie
  }

  return {
    getCookie,
    setCookie,
    deleteCookie,
  }
}
