/**
 * Cookie 策略管理工具类
 * 
 * 提供功能:
 * - 设置/获取/删除 Cookie (支持现代属性)
 * - SameSite/Lax/None 配置
 * - Secure/HttpOnly 标志位控制
 */

export class CookiePolicy {
  /**
   * 设置 Cookie
   * 
   * @param name - Cookie 名称
   * @param value - Cookie 值
   * @param options - 可选配置项
   * @param options.maxAge - 过期时间(秒), 默认3600
   * @param options.httpOnly - 是否 HttpOnly (防止 XSS), 默认false
   * @param options.secure - 是否 Secure (仅 HTTPS), 默认true
   * @param options.sameSite - SameSite 策略 ('Lax' | 'Strict' | 'None'), 默认'Lax'
   * @param options.domain - 域名, 默认'.imageteach.tech'
   * @param options.path - 路径, 默认'/'
   */
  static setCookie(
    name: string,
    value: string,
    options: {
      maxAge?: number;
      httpOnly?: boolean;
      secure?: boolean;
      sameSite?: 'Lax' | 'Strict' | 'None';
      domain?: string;
      path?: string;
    } = {}
  ): void {
    const defaults = {
      maxAge: 3600,           // 1小时
      httpOnly: false,        // 允许前端读取
      secure: true,           // HTTPS 传输
      sameSite: 'Lax',        // 防止 CSRF
      domain: '.imageteach.tech',
      path: '/'
    };

    const finalOptions = { ...defaults, ...options };
    
    // 构建 Cookie 字符串
    const parts = [
      `${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
      `Max-Age=${finalOptions.maxAge}`,
      finalOptions.httpOnly ? 'HttpOnly' : '',
      finalOptions.secure ? 'Secure' : '',
      `SameSite=${finalOptions.sameSite}`,
      `Domain=${finalOptions.domain}`,
      `Path=${finalOptions.path}`
    ].filter(Boolean).join('; ');

    document.cookie = parts;
  }

  /**
   * 获取 Cookie 值
   * @param name - Cookie 名称
   * @returns Cookie 值或 null
   */
  static getCookie(name: string): string | null {
    const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
    return match ? decodeURIComponent(match[2]) : null;
  }

  /**
   * 删除 Cookie
   * @param name - Cookie 名称
   */
  static deleteCookie(name: string): void {
    document.cookie = `${name}=; Max-Age=0; Path=/`;
  }

  /**
   * 获取所有 Cookie
   * @returns Cookie 键值对对象
   */
  static getAllCookies(): Record<string, string> {
    const cookies: Record<string, string> = {};
    document.cookie.split('; ').forEach(cookie => {
      const [name, ...valueParts] = cookie.split('=');
      if (name) {
        cookies[name] = valueParts.join('=');
      }
    });
    return cookies;
  }
}

// 导出便捷方法
export const setCookie = CookiePolicy.setCookie.bind(CookiePolicy);
export const getCookie = CookiePolicy.getCookie.bind(CookiePolicy);
export const deleteCookie = CookiePolicy.deleteCookie.bind(CookiePolicy);
