/**
 * 穿搭方案收藏API服务
 * 遵循 Tauri 开发规范的API服务设计原则
 */

import { invoke } from '@tauri-apps/api/core';
import {
  OutfitFavorite,
  SaveOutfitToFavoritesRequest,
  SaveOutfitToFavoritesResponse,
  GetFavoriteOutfitsResponse,
  SearchMaterialsByFavoriteRequest,
  CompareOutfitFavoritesRequest,
  CompareOutfitFavoritesResponse,
} from '../types/outfitFavorite';
import { OutfitRecommendation } from '../types/outfitRecommendation';
import { MaterialSearchResponse } from '../types/materialSearch';

export class OutfitFavoriteService {
  /**
   * 保存方案到收藏
   */
  static async saveToFavorites(
    recommendation: OutfitRecommendation,
    customName?: string
  ): Promise<SaveOutfitToFavoritesResponse> {
    try {
      const request: SaveOutfitToFavoritesRequest = {
        recommendation,
        custom_name: customName,
      };

      console.log('💖 保存方案到收藏:', request);

      const response = await invoke<SaveOutfitToFavoritesResponse>(
        'save_outfit_to_favorites',
        { request }
      );

      console.log('✅ 方案收藏成功:', response);
      return response;
    } catch (error) {
      console.error('❌ 方案收藏失败:', error);
      throw new Error(`方案收藏失败: ${error}`);
    }
  }

  /**
   * 获取所有收藏的方案
   */
  static async getFavoriteOutfits(): Promise<GetFavoriteOutfitsResponse> {
    try {
      console.log('📋 获取收藏方案列表');

      const response = await invoke<GetFavoriteOutfitsResponse>(
        'get_favorite_outfits'
      );

      console.log('✅ 获取收藏列表成功:', response);
      return response;
    } catch (error) {
      console.error('❌ 获取收藏列表失败:', error);
      throw new Error(`获取收藏列表失败: ${error}`);
    }
  }

  /**
   * 从收藏中移除方案
   */
  static async removeFromFavorites(favoriteId: string): Promise<boolean> {
    try {
      console.log('🗑️ 从收藏中移除方案:', favoriteId);

      const response = await invoke<boolean>(
        'remove_from_favorites',
        { favoriteId }
      );

      console.log('✅ 收藏移除成功:', response);
      return response;
    } catch (error) {
      console.error('❌ 移除收藏失败:', error);
      throw new Error(`移除收藏失败: ${error}`);
    }
  }

  /**
   * 基于收藏方案检索素材
   */
  static async searchMaterialsByFavorite(
    favoriteId: string,
    page: number = 1,
    pageSize: number = 9
  ): Promise<MaterialSearchResponse> {
    try {
      const request: SearchMaterialsByFavoriteRequest = {
        favorite_id: favoriteId,
        page,
        page_size: pageSize,
      };

      console.log('🔍 基于收藏方案检索素材:', request);

      const response = await invoke<MaterialSearchResponse>(
        'search_materials_by_favorite',
        { request }
      );

      console.log('✅ 素材检索成功:', response);
      return response;
    } catch (error) {
      console.error('❌ 素材检索失败:', error);
      throw new Error(`素材检索失败: ${error}`);
    }
  }

  /**
   * 对比两个收藏方案的素材检索结果
   */
  static async compareOutfitFavorites(
    favoriteId1: string,
    favoriteId2: string,
    page: number = 1,
    pageSize: number = 9
  ): Promise<CompareOutfitFavoritesResponse> {
    try {
      const request: CompareOutfitFavoritesRequest = {
        favorite_id_1: favoriteId1,
        favorite_id_2: favoriteId2,
        page,
        page_size: pageSize,
      };

      console.log('🔄 对比收藏方案:', request);

      const response = await invoke<CompareOutfitFavoritesResponse>(
        'compare_outfit_favorites',
        { request }
      );

      console.log('✅ 方案对比成功:', response);
      return response;
    } catch (error) {
      console.error('❌ 方案对比失败:', error);
      throw new Error(`方案对比失败: ${error}`);
    }
  }

  /**
   * 检查方案是否已收藏
   */
  static async isOutfitFavorited(recommendationId: string): Promise<boolean> {
    try {
      console.log('🔍 检查方案收藏状态:', recommendationId);

      const response = await invoke<boolean>(
        'is_outfit_favorited',
        { recommendationId }
      );

      console.log('✅ 收藏状态检查完成:', response);
      return response;
    } catch (error) {
      console.error('❌ 检查收藏状态失败:', error);
      throw new Error(`检查收藏状态失败: ${error}`);
    }
  }

  /**
   * 获取收藏方案的显示名称
   */
  static getDisplayName(favorite: OutfitFavorite): string {
    return favorite.custom_name || favorite.recommendation_data.title;
  }

  /**
   * 获取收藏方案的描述
   */
  static getDescription(favorite: OutfitFavorite): string {
    return favorite.recommendation_data.description;
  }

  /**
   * 获取收藏方案的风格标签
   */
  static getStyleTags(favorite: OutfitFavorite): string[] {
    return favorite.recommendation_data.style_tags;
  }

  /**
   * 获取收藏方案的适合场合
   */
  static getOccasions(favorite: OutfitFavorite): string[] {
    return favorite.recommendation_data.occasions;
  }

  /**
   * 格式化收藏时间
   */
  static formatCreatedAt(favorite: OutfitFavorite): string {
    const date = new Date(favorite.created_at);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  }

  /**
   * 过滤收藏方案
   */
  static filterFavorites(
    favorites: OutfitFavorite[],
    searchTerm: string
  ): OutfitFavorite[] {
    if (!searchTerm.trim()) {
      return favorites;
    }

    const term = searchTerm.toLowerCase();
    return favorites.filter(favorite => {
      const displayName = this.getDisplayName(favorite).toLowerCase();
      const description = this.getDescription(favorite).toLowerCase();
      const styleTags = this.getStyleTags(favorite).join(' ').toLowerCase();
      const occasions = this.getOccasions(favorite).join(' ').toLowerCase();

      return (
        displayName.includes(term) ||
        description.includes(term) ||
        styleTags.includes(term) ||
        occasions.includes(term)
      );
    });
  }

  /**
   * 排序收藏方案
   */
  static sortFavorites(
    favorites: OutfitFavorite[],
    sortBy: string
  ): OutfitFavorite[] {
    const sorted = [...favorites];

    switch (sortBy) {
      case 'created_at_desc':
        return sorted.sort((a, b) => 
          new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
        );
      case 'created_at_asc':
        return sorted.sort((a, b) => 
          new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
        );
      case 'custom_name_asc':
        return sorted.sort((a, b) => 
          this.getDisplayName(a).localeCompare(this.getDisplayName(b))
        );
      case 'custom_name_desc':
        return sorted.sort((a, b) => 
          this.getDisplayName(b).localeCompare(this.getDisplayName(a))
        );
      default:
        return sorted;
    }
  }
}
