import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import library from './library';

/**
 * cookie パッケージを v1(parse/serialize) から v2(parseCookie/stringifySetCookie) へ
 * 移行した際の $.cookie ポリフィルの挙動を保証する特徴付けテスト。
 */
describe('library() の $.cookie ポリフィル', () => {
  beforeEach(() => {
    window.ACMS.Config = { ...window.ACMS.Config, fulltimeSSL: '0' };
    window.ACMS.Library = {};
    library();
  });

  afterEach(() => {
    document.cookie.split(';').forEach((cookie) => {
      const name = cookie.split('=')[0].trim();
      if (name) {
        document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
      }
    });
  });

  it('文字列値を設定すると同名で取得できる', () => {
    $.cookie('acms-test-key', 'acms-test-value');
    expect($.cookie('acms-test-key')).toBe('acms-test-value');
  });

  it('name を省略すると全 cookie を連想配列で返す', () => {
    $.cookie('acms-test-key', 'acms-test-value');
    const cookies = $.cookie();
    expect(cookies['acms-test-key']).toBe('acms-test-value');
  });

  it('存在しない key は null を返す', () => {
    expect($.cookie('acms-not-exist-key')).toBeNull();
  });

  it('value に null を渡すと cookie を削除する', () => {
    $.cookie('acms-test-key', 'acms-test-value');
    expect($.cookie('acms-test-key')).toBe('acms-test-value');
    $.cookie('acms-test-key', null);
    expect($.cookie('acms-test-key')).toBeNull();
  });

  it('expires を日数指定すると Set-Cookie 文字列の生成に例外を投げない', () => {
    expect(() => $.cookie('acms-test-key', 'v', { expires: 7 })).not.toThrow();
    expect($.cookie('acms-test-key')).toBe('v');
  });
});
