import api from '../../../shared/utils/api';

export interface Experience {
  id: string;
  experienceType: string;
  content: string;
  scenario: string;
  confidence: number;
  relatedCategory: string;
  sourceConversationIds: string[];
  verificationStatus: string;
  usageCount: number;
  positiveCount: number;
  negativeCount: number;
  isActive: boolean;
  createdAt: string;
}

export interface ExperienceListResponse {
  items: Experience[];
  total: number;
}

export interface ExperienceStatistics {
  total: number;
  byStatus: Record<string, number>;
  byType: Record<string, number>;
}

export interface CreateExperienceDto {
  experienceType: string;
  content: string;
  scenario: string;
  relatedCategory?: string;
  confidence?: number;
}

export const experienceApi = {
  getPendingExperiences: async (type?: string): Promise<ExperienceListResponse> => {
    const params = new URLSearchParams();
    if (type) params.append('type', type);
    const response = await api.get(`/memory/experience/pending?${params}`);
    return response.data.data;
  },

  getStatistics: async (): Promise<ExperienceStatistics> => {
    const response = await api.get('/memory/experience/statistics');
    return response.data.data;
  },

  approveExperience: async (id: string, adminId: string): Promise<void> => {
    await api.post(`/memory/experience/${id}/approve`, { adminId });
  },

  rejectExperience: async (id: string, adminId: string): Promise<void> => {
    await api.post(`/memory/experience/${id}/reject`, { adminId });
  },

  createExperience: async (dto: CreateExperienceDto): Promise<Experience> => {
    // 管理员手动创建：先创建（PENDING），再自动批准（APPROVED + isActive）
    const createResponse = await api.post('/memory/experience', {
      ...dto,
      sourceConversationId: 'admin-manual',
      confidence: dto.confidence ?? 80,
    });
    const created = createResponse.data.data as Experience;

    // 自动批准 — 管理员手动创建的经验无需再审核
    await api.post(`/memory/experience/${created.id}/approve`, {
      adminId: 'admin-manual',
    });

    return created;
  },

  runEvolution: async (hoursBack: number = 24, limit: number = 50): Promise<{
    conversationsAnalyzed: number;
    experiencesExtracted: number;
  }> => {
    const response = await api.post('/evolution/run', { hoursBack, limit });
    return response.data.data;
  },
};
