/**
 * MiniProgram Navigation Adapter
 *
 * 基于 Taro 的导航适配器实现
 */

import type { INavigationAdapter, NavigateOptions } from './interface';

export class MiniprogramNavigationAdapter implements INavigationAdapter {
  private Taro: any;

  constructor(Taro: any) {
    this.Taro = Taro;
  }

  private buildUrl(url: string, params?: Record<string, any>): string {
    if (!params || Object.keys(params).length === 0) {
      return url;
    }

    const queryString = Object.entries(params)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');

    return `${url}?${queryString}`;
  }

  async navigateTo(options: NavigateOptions): Promise<void> {
    const url = this.buildUrl(options.url, options.params);

    if (options.replace) {
      await this.Taro.redirectTo({ url });
    } else {
      await this.Taro.navigateTo({ url });
    }
  }

  navigateBack(delta: number = 1): void {
    this.Taro.navigateBack({ delta });
  }

  async redirectTo(options: NavigateOptions): Promise<void> {
    const url = this.buildUrl(options.url, options.params);
    await this.Taro.redirectTo({ url });
  }

  getCurrentRoute(): string {
    const pages = this.Taro.getCurrentPages();
    const currentPage = pages[pages.length - 1];
    return currentPage?.route || '';
  }
}
