import { Headers } from '../../../lib/headers/Headers.js'
import { CookieParser } from '../../../cookies/CookieParser.js'

/**
 * Handles cookie exchange when redirecting the request.
 */
export function processRedirectCookies(
  responseCookies: string,
  location: string,
  requestUrl: string,
  requestHeaders: string
): string {
  const received = CookieParser.parse(requestUrl, responseCookies)
  const forwardCookies = CookieParser.filterCookies(received, location)
  const headers = new Headers(requestHeaders)
  headers.delete('cookie')
  if (forwardCookies.length) {
    const parts: string[] = []
    forwardCookies.forEach((cookie) => {
      parts.push(cookie.toString())
    })
    headers.set('cookie', parts.join('; '))
  }
  return headers.toString()
}
