import type {
  PaginatedFunnelEntries,
  FunnelEntriesParams,
  FunnelClientDetail,
  AssignClientDto,
  MoveStageDto,
  TransferClientDto,
  RefuseClientDto,
  FunnelConversionStats,
  FunnelDistribution,
  FunnelEntry,
  TrainerOption,
} from '../types/funnel';
import { api } from './api';

export const funnelService = {
  async getFunnelEntries(params?: FunnelEntriesParams): Promise<PaginatedFunnelEntries> {
    const response = await api.get<{ data: FunnelEntry[]; nextCursor: string | null; hasMore: boolean }>('/funnel', {
      params: {
        stage: params?.stage,
        trainerId: params?.trainerId,
        cursor: params?.cursor,
        limit: params?.limit,
      },
    });
    return {
      data: response.data,
      cursor: response.nextCursor,
      hasMore: response.hasMore,
      total: response.data.length,
    };
  },

  async getClientFunnel(clientId: string): Promise<FunnelClientDetail> {
    const entries = await api.get<FunnelEntry[]>(`/funnel/client/${clientId}`);
    const sorted = Array.isArray(entries) ? entries : [];
    const latest = sorted[0];
    const history = sorted.map((e) => ({
      id: e.id,
      fromStage: (e as any).previousStage ?? null,
      toStage: e.stage,
      comment: e.comment,
      performedBy: e.trainerId ?? '',
      performedByName: e.trainer
        ? `${e.trainer.firstName} ${e.trainer.lastName}`
        : '',
      createdAt: e.createdAt,
    }));
    return { entry: latest, history };
  },

  async assignClient(dto: AssignClientDto): Promise<FunnelEntry> {
    return api.post<FunnelEntry>('/funnel/assign', dto);
  },

  async moveStage(clientId: string, dto: MoveStageDto): Promise<FunnelEntry> {
    return api.post<FunnelEntry>(`/funnel/${clientId}/move`, dto);
  },

  async transferClient(clientId: string, dto: TransferClientDto): Promise<FunnelEntry> {
    return api.post<FunnelEntry>(`/funnel/${clientId}/transfer`, dto);
  },

  async refuseClient(clientId: string, dto: RefuseClientDto): Promise<FunnelEntry> {
    return api.post<FunnelEntry>(`/funnel/${clientId}/refuse`, dto);
  },

  async getConversionStats(dateFrom?: string, dateTo?: string): Promise<FunnelConversionStats> {
    return api.get<FunnelConversionStats>('/funnel/stats', {
      params: {
        dateFrom,
        dateTo,
      },
    });
  },

  async getDistribution(): Promise<FunnelDistribution[]> {
    return api.get<FunnelDistribution[]>('/funnel/distribution');
  },

  async getTrainers(): Promise<TrainerOption[]> {
    return api.get<TrainerOption[]>('/users/trainers');
  },
};
