import type { Context } from 'hono';

/**
 * Cookie配置接口
 */
export interface CookieConfig {
  /** Cookie名称 */
  name: string;
  /** 过期时间（秒） */
  maxAge?: number;
  /** 路径 */
  path?: string;
  /** 域名 */
  domain?: string;
  /** 是否安全连接 */
  secure?: boolean;
  /** HttpOnly标志 */
  httpOnly?: boolean;
  /** SameSite属性 */
  sameSite?: 'Strict' | 'Lax' | 'None';
}

/**
 * Cookie工具类
 */
export class CookieUtils {
  private static readonly DEFAULT_SESSION_COOKIE_NAME = 'oidc-session';
  private static readonly DEFAULT_MAX_AGE = 24 * 60 * 60; // 24小时

  /**
   * 设置Cookie
   */
  static setCookie(c: Context, value: string, config: Partial<CookieConfig> = {}): void {
    const {
      name = this.DEFAULT_SESSION_COOKIE_NAME,
      maxAge = this.DEFAULT_MAX_AGE,
      path = '/',
      secure = process.env.NODE_ENV === 'production',
      httpOnly = true,
      sameSite = process.env.NODE_ENV === 'production' ? 'None' : 'Lax'
    } = config;

    const cookieParts = [
      `${name}=${encodeURIComponent(value)}`,
      `Path=${path}`,
      `Max-Age=${maxAge}`
    ];

    if (httpOnly) cookieParts.push('HttpOnly');
    if (secure) cookieParts.push('Secure');
    cookieParts.push(`SameSite=${sameSite}`);

    c.header('Set-Cookie', cookieParts.join('; '));
  }

  /**
   * 设置会话Cookie
   */
  static setSessionCookie(c: Context, sessionId: string, maxAge?: number): void {
    this.setCookie(c, sessionId, {
      name: this.DEFAULT_SESSION_COOKIE_NAME,
      maxAge: maxAge || this.DEFAULT_MAX_AGE
    });
  }

  /**
   * 清除Cookie
   */
  static clearCookie(c: Context, name: string = this.DEFAULT_SESSION_COOKIE_NAME): void {
    this.setCookie(c, '', {
      name,
      maxAge: 0
    });
  }

  /**
   * 清除会话Cookie
   */
  static clearSessionCookie(c: Context): void {
    this.clearCookie(c, this.DEFAULT_SESSION_COOKIE_NAME);
  }

  /**
   * 获取Cookie值
   */
  static getCookie(c: Context, name: string): string | null {
    const cookieHeader = c.req.header('Cookie');
    if (!cookieHeader) return null;

    const regex = new RegExp(`(?:^|; )${name}=([^;]*)`);
    const match = cookieHeader.match(regex);
    
    return match && match[1] ? decodeURIComponent(match[1]) : null;
  }

  /**
   * 获取会话ID从Cookie
   */
  static getSessionIdFromCookie(c: Context): string | null {
    return this.getCookie(c, this.DEFAULT_SESSION_COOKIE_NAME);
  }

  /**
   * 解析所有Cookie
   */
  static parseAllCookies(c: Context): Record<string, string> {
    const cookieHeader = c.req.header('Cookie');
    if (!cookieHeader) return {};

    const cookies: Record<string, string> = {};
    
    cookieHeader.split(';').forEach(cookie => {
      const [name, ...rest] = cookie.trim().split('=');
      if (name && rest.length > 0) {
        cookies[name] = decodeURIComponent(rest.join('='));
      }
    });

    return cookies;
  }
} 