import { describe, it, expect } from 'vitest'
import { parseContentDispositionFilename } from './mutations'

describe('parseContentDispositionFilename', () => {
  it('returns null for undefined / empty', () => {
    expect(parseContentDispositionFilename(undefined)).toBeNull()
    expect(parseContentDispositionFilename('')).toBeNull()
  })

  it('parses RFC 2183 (legacy) quoted filename', () => {
    expect(
      parseContentDispositionFilename('attachment; filename="report.csv"'),
    ).toBe('report.csv')
  })

  it('parses RFC 2183 unquoted filename', () => {
    expect(
      parseContentDispositionFilename('attachment; filename=report.csv'),
    ).toBe('report.csv')
  })

  it('parses RFC 5987 UTF-8 encoded filename', () => {
    const result = parseContentDispositionFilename(
      "attachment; filename*=UTF-8''%D0%9E%D1%82%D1%87%D1%91%D1%82.csv",
    )
    expect(result).toBe('Отчёт.csv')
  })

  it('prefers RFC 5987 when both forms present', () => {
    const result = parseContentDispositionFilename(
      "attachment; filename=fallback.csv; filename*=UTF-8''%D0%9F%D1%80%D0%B0%D0%B9%D1%81.csv",
    )
    expect(result).toBe('Прайс.csv')
  })

  it('falls back gracefully for ISO-8859-1 (decode may not produce correct chars)', () => {
    // ISO-8859-1 single-byte encoding не decodes via decodeURIComponent —
    // browser TextDecoder с label='iso-8859-1' нужен. Сейчас fallback к raw
    // value (без decode). Acceptable degradation — backend нужно использовать
    // UTF-8 для non-ASCII filenames (RFC 5987 recommends).
    const result = parseContentDispositionFilename(
      "attachment; filename*=ISO-8859-1''r%E9sum%E9.csv",
    )
    // Result either decoded or raw — main thing: not null, no throw
    expect(result).not.toBeNull()
    expect(typeof result).toBe('string')
  })

  it('returns raw value if decodeURIComponent fails', () => {
    // Malformed % encoding — decode throws, fallback к raw value
    const result = parseContentDispositionFilename(
      "attachment; filename*=UTF-8''broken%ZZ.csv",
    )
    // Не throws — graceful fallback
    expect(result).toBe('broken%ZZ.csv')
  })
})
