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

// ==================== DTOs ====================

export interface DailyStatisticsDto {
  statDate: string;
  dimension: string;
  dimensionValue: string | null;
  newUsers: number;
  newRegisteredUsers: number;
  activeUsers: number;
  newConversations: number;
  totalMessages: number;
  userMessages: number;
  assistantMessages: number;
  avgConversationTurns: number;
  newOrders: number;
  paidOrders: number;
  totalOrderAmount: number;
  totalPaidAmount: number;
  refundedOrders: number;
  refundAmount: number;
  conversionCount: number;
  conversionRate: number;
  totalInputTokens: number;
  totalOutputTokens: number;
  estimatedApiCost: number;
}

export interface TrendDataPoint {
  date: string;
  value: number;
}

export type TrendData = Record<string, TrendDataPoint[]>;

export interface FinancialReportDto {
  id: string;
  reportMonth: string;
  totalRevenue: number;
  assessmentRevenue: number;
  consultationRevenue: number;
  otherRevenue: number;
  totalRefunds: number;
  netRevenue: number;
  apiCost: number;
  paymentFees: number;
  otherCosts: number;
  totalCosts: number;
  grossProfit: number;
  grossMargin: number;
  totalOrders: number;
  successfulOrders: number;
  avgOrderAmount: number;
  revenueByCategory: Record<string, number>;
  revenueByChannel: Record<string, number>;
  status: 'DRAFT' | 'CONFIRMED' | 'LOCKED';
  confirmedBy: string | null;
  confirmedAt: string | null;
  notes: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface AuditLogDto {
  id: string;
  actorId: string | null;
  actorType: 'USER' | 'ADMIN' | 'SYSTEM';
  actorName: string | null;
  action: string;
  entityType: string;
  entityId: string | null;
  oldValues: Record<string, unknown> | null;
  newValues: Record<string, unknown> | null;
  changedFields: string[] | null;
  description: string | null;
  ipAddress: string | null;
  userAgent: string | null;
  requestId: string | null;
  result: 'SUCCESS' | 'FAILED';
  errorMessage: string | null;
  createdAt: string;
}

export interface PaginatedAuditLogs {
  items: AuditLogDto[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

export interface AuditLogQueryParams {
  actorType?: string;
  actorId?: string;
  action?: string;
  entityType?: string;
  entityId?: string;
  result?: string;
  startDate?: string;
  endDate?: string;
  page?: number;
  pageSize?: number;
}

// ==================== API ====================

export const analyticsApi = {
  // Statistics
  getTodayStatistics: async (): Promise<DailyStatisticsDto | null> => {
    const response = await api.get('/analytics/statistics/today');
    return response.data.data;
  },

  getDailyStatistics: async (startDate: string, endDate: string, dimension?: string): Promise<DailyStatisticsDto[]> => {
    const response = await api.get('/analytics/statistics/daily', {
      params: { startDate, endDate, dimension },
    });
    return response.data.data;
  },

  getTrendData: async (days: number, metrics: string[]): Promise<TrendData> => {
    const response = await api.get('/analytics/statistics/trend', {
      params: { days: days.toString(), metrics: metrics.join(',') },
    });
    return response.data.data;
  },

  getStatisticsByChannel: async (startDate: string, endDate: string): Promise<DailyStatisticsDto[]> => {
    const response = await api.get('/analytics/statistics/by-channel', {
      params: { startDate, endDate },
    });
    return response.data.data;
  },

  getStatisticsByCategory: async (startDate: string, endDate: string): Promise<DailyStatisticsDto[]> => {
    const response = await api.get('/analytics/statistics/by-category', {
      params: { startDate, endDate },
    });
    return response.data.data;
  },

  refreshStatistics: async (date?: string): Promise<{ success: boolean; message: string }> => {
    const response = await api.post('/analytics/statistics/refresh', { date });
    return response.data.data;
  },

  backfillStatistics: async (startDate: string, endDate: string): Promise<{ success: boolean; message: string }> => {
    const response = await api.post('/analytics/statistics/backfill', { startDate, endDate });
    return response.data.data;
  },

  // Financial Reports
  listFinancialReports: async (year?: number, status?: string): Promise<FinancialReportDto[]> => {
    const response = await api.get('/analytics/financial-reports', {
      params: { year: year?.toString(), status },
    });
    return response.data.data;
  },

  getFinancialReport: async (month: string): Promise<FinancialReportDto> => {
    const response = await api.get(`/analytics/financial-reports/${month}`);
    return response.data.data;
  },

  generateFinancialReport: async (month: string): Promise<{ success: boolean; message: string }> => {
    const response = await api.post('/analytics/financial-reports/generate', { month });
    return response.data.data;
  },

  confirmFinancialReport: async (month: string): Promise<FinancialReportDto> => {
    const response = await api.put(`/analytics/financial-reports/${month}/confirm`);
    return response.data.data;
  },

  lockFinancialReport: async (month: string): Promise<FinancialReportDto> => {
    const response = await api.put(`/analytics/financial-reports/${month}/lock`);
    return response.data.data;
  },

  updateReportNotes: async (month: string, notes: string): Promise<FinancialReportDto> => {
    const response = await api.put(`/analytics/financial-reports/${month}/notes`, { notes });
    return response.data.data;
  },

  // Audit Logs
  getAuditLogs: async (params: AuditLogQueryParams): Promise<PaginatedAuditLogs> => {
    const response = await api.get('/audit/logs', { params });
    return response.data.data;
  },

  getAuditLog: async (id: string): Promise<AuditLogDto> => {
    const response = await api.get(`/audit/logs/${id}`);
    return response.data.data;
  },

  getEntityHistory: async (entityType: string, entityId: string): Promise<AuditLogDto[]> => {
    const response = await api.get(`/audit/logs/entity/${entityType}/${entityId}`);
    return response.data.data;
  },

  getActorHistory: async (actorId: string, page = 1, pageSize = 50): Promise<PaginatedAuditLogs> => {
    const response = await api.get(`/audit/logs/actor/${actorId}`, {
      params: { page, pageSize },
    });
    return response.data.data;
  },

  getActionTypes: async (): Promise<{ actions: string[] }> => {
    const response = await api.get('/audit/logs/actions');
    return response.data.data;
  },

  getEntityTypes: async (): Promise<{ entityTypes: string[] }> => {
    const response = await api.get('/audit/logs/entity-types');
    return response.data.data;
  },
};
