/**
 * 用户标签服务
 * 负责用户画像相关的API调用
 */

import apiClient from '@/infrastructure/api/client';
import { API_ENDPOINTS } from '@/infrastructure/api/endpoints';

// =====================
// 类型定义
// =====================

/** 标签类型 */
export type TagType = 'MANUAL' | 'AUTO' | 'COMPUTED' | 'SYSTEM';

/** 标签值类型 */
export type TagValueType = 'BOOLEAN' | 'ENUM' | 'NUMBER' | 'STRING';

/** 标签分类 */
export interface TagCategory {
  id: string;
  code: string;
  name: string;
  description: string | null;
  sortOrder: number;
  isEnabled: boolean;
  createdAt: string;
  updatedAt: string;
}

/** 用户标签 */
export interface UserTag {
  id: string;
  categoryId: string | null;
  categoryName?: string;
  code: string;
  name: string;
  description: string | null;
  color: string | null;
  type: TagType;
  valueType: TagValueType;
  enumValues: string[] | null;
  ruleId: string | null;
  isAdvertisable: boolean;
  estimatedUsers: number | null;
  isEnabled: boolean;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
}

/** 用户标签分配 */
export interface UserTagAssignment {
  id: string;
  accountSequence: string;
  tagId: string;
  tagCode: string;
  tagName: string;
  value: string | null;
  source: string;
  expiresAt: string | null;
  assignedAt: string;
}

/** 创建标签分类请求 */
export interface CreateCategoryRequest {
  code: string;
  name: string;
  description?: string;
  sortOrder?: number;
}

/** 更新标签分类请求 */
export interface UpdateCategoryRequest {
  name?: string;
  description?: string;
  sortOrder?: number;
  isEnabled?: boolean;
}

/** 创建标签请求 */
export interface CreateTagRequest {
  categoryId?: string;
  code: string;
  name: string;
  description?: string;
  color?: string;
  type?: TagType;
  valueType?: TagValueType;
  enumValues?: string[];
  isAdvertisable?: boolean;
  sortOrder?: number;
}

/** 更新标签请求 */
export interface UpdateTagRequest {
  categoryId?: string;
  name?: string;
  description?: string;
  color?: string;
  type?: TagType;
  valueType?: TagValueType;
  enumValues?: string[];
  isAdvertisable?: boolean;
  isEnabled?: boolean;
  sortOrder?: number;
}

/** 标签列表查询参数 */
export interface ListTagsParams {
  categoryId?: string;
  type?: TagType;
  isEnabled?: boolean;
  isAdvertisable?: boolean;
  limit?: number;
  offset?: number;
}

/** 分页响应 */
export interface PaginatedResponse<T> {
  items: T[];
  total: number;
}

/** 分配标签请求 */
export interface AssignTagRequest {
  accountSequence: string;
  tagId: string;
  value?: string;
  source?: string;
  expiresAt?: string;
}

/** 移除标签请求 */
export interface RemoveTagRequest {
  accountSequence: string;
  tagId: string;
}

/** 批量分配标签请求 */
export interface BatchAssignTagRequest {
  accountSequences: string[];
  tagId: string;
  value?: string;
  reason?: string;
}

/** 批量操作结果 */
export interface BatchOperationResult {
  success: number;
  failed: number;
  errors: Array<{ accountSequence: string; error: string }>;
}

/** 标签下的用户 */
export interface TagUserItem {
  accountSequence: string;
  value: string | null;
  assignedAt: string;
  assignedBy: string | null;
}

// =====================
// 选项常量
// =====================

/** 标签类型选项 */
export const TAG_TYPE_OPTIONS = [
  { value: 'MANUAL', label: '手动标签', color: 'blue' },
  { value: 'AUTO', label: '自动标签', color: 'green' },
  { value: 'COMPUTED', label: '计算标签', color: 'purple' },
  { value: 'SYSTEM', label: '系统标签', color: 'gray' },
] as const;

/** 标签值类型选项 */
export const TAG_VALUE_TYPE_OPTIONS = [
  { value: 'BOOLEAN', label: '布尔型' },
  { value: 'ENUM', label: '枚举型' },
  { value: 'NUMBER', label: '数值型' },
  { value: 'STRING', label: '字符串' },
] as const;

/** 预设颜色 */
export const TAG_COLORS = [
  '#EF4444', // red
  '#F97316', // orange
  '#EAB308', // yellow
  '#22C55E', // green
  '#14B8A6', // teal
  '#3B82F6', // blue
  '#8B5CF6', // purple
  '#EC4899', // pink
  '#6B7280', // gray
];

// =====================
// 服务方法
// =====================

export const userTagService = {
  // =====================
  // 标签分类
  // =====================

  /** 获取所有标签分类 */
  async getCategories(): Promise<TagCategory[]> {
    return apiClient.get(API_ENDPOINTS.USER_TAGS.CATEGORIES);
  },

  /** 创建标签分类 */
  async createCategory(data: CreateCategoryRequest): Promise<TagCategory> {
    return apiClient.post(API_ENDPOINTS.USER_TAGS.CATEGORIES, data);
  },

  /** 更新标签分类 */
  async updateCategory(id: string, data: UpdateCategoryRequest): Promise<TagCategory> {
    return apiClient.put(API_ENDPOINTS.USER_TAGS.CATEGORY_DETAIL(id), data);
  },

  /** 删除标签分类 */
  async deleteCategory(id: string): Promise<void> {
    return apiClient.delete(API_ENDPOINTS.USER_TAGS.CATEGORY_DETAIL(id));
  },

  // =====================
  // 标签
  // =====================

  /** 获取标签列表 */
  async getTags(params: ListTagsParams = {}): Promise<PaginatedResponse<UserTag>> {
    return apiClient.get(API_ENDPOINTS.USER_TAGS.LIST, { params });
  },

  /** 获取标签详情 */
  async getTag(id: string): Promise<UserTag> {
    return apiClient.get(API_ENDPOINTS.USER_TAGS.DETAIL(id));
  },

  /** 创建标签 */
  async createTag(data: CreateTagRequest): Promise<UserTag> {
    return apiClient.post(API_ENDPOINTS.USER_TAGS.CREATE, data);
  },

  /** 更新标签 */
  async updateTag(id: string, data: UpdateTagRequest): Promise<UserTag> {
    return apiClient.put(API_ENDPOINTS.USER_TAGS.UPDATE(id), data);
  },

  /** 删除标签 */
  async deleteTag(id: string): Promise<void> {
    return apiClient.delete(API_ENDPOINTS.USER_TAGS.DELETE(id));
  },

  /** 预估标签用户数 */
  async estimateUsers(id: string): Promise<{ count: number }> {
    return apiClient.get(API_ENDPOINTS.USER_TAGS.ESTIMATE_USERS(id));
  },

  // =====================
  // 用户标签分配
  // =====================

  /** 给用户分配标签 */
  async assignTag(data: AssignTagRequest): Promise<{ success: boolean }> {
    return apiClient.post(API_ENDPOINTS.USER_TAGS.ASSIGN, data);
  },

  /** 移除用户标签 */
  async removeTag(data: RemoveTagRequest): Promise<{ success: boolean }> {
    return apiClient.post(API_ENDPOINTS.USER_TAGS.REMOVE, data);
  },

  /** 批量分配标签 */
  async batchAssignTag(data: BatchAssignTagRequest): Promise<BatchOperationResult> {
    return apiClient.post(API_ENDPOINTS.USER_TAGS.BATCH_ASSIGN, data);
  },

  /** 获取用户的标签 */
  async getUserTags(accountSequence: string): Promise<UserTagAssignment[]> {
    return apiClient.get(API_ENDPOINTS.USER_TAGS.USER_TAGS(accountSequence));
  },

  /** 获取标签下的用户列表 */
  async getTagUsers(tagId: string, params: { limit?: number; offset?: number } = {}): Promise<PaginatedResponse<TagUserItem>> {
    return apiClient.get(API_ENDPOINTS.USER_TAGS.TAG_USERS(tagId), { params });
  },
};

export default userTagService;
