import apiClient from './client';

export type ActivityType = 'feeding' | 'sleep' | 'diaper' | 'medication' | 'milestone' | 'note';

export interface Activity {
  id: string;
  childId: string;
  type: ActivityType;
  timestamp: string;
  data: any;
  notes?: string;
  loggedBy: string;
  createdAt: string;
}

export interface CreateActivityData {
  type: ActivityType;
  timestamp: string;
  data: any;
  notes?: string;
}

export interface UpdateActivityData extends Partial<CreateActivityData> {}

export interface DailySummary {
  date: string;
  feedingCount: number;
  sleepTotalMinutes: number;
  diaperCount: number;
  medicationCount: number;
  activities: Activity[];
}

export const trackingApi = {
  // Get all activities for a child
  getActivities: async (
    childId: string,
    type?: ActivityType,
    startDate?: string,
    endDate?: string
  ): Promise<Activity[]> => {
    const params: any = { childId };
    if (type) params.type = type;
    if (startDate) params.startDate = startDate;
    if (endDate) params.endDate = endDate;

    const response = await apiClient.get('/api/v1/activities', { params });
    // Transform backend response to frontend format
    const activities = response.data.data.activities.map((activity: any) => ({
      ...activity,
      timestamp: activity.startedAt, // Frontend expects timestamp
      data: activity.metadata,        // Frontend expects data
    }));
    return activities;
  },

  // Get a specific activity
  getActivity: async (id: string): Promise<Activity> => {
    const response = await apiClient.get(`/api/v1/activities/${id}`);
    const activity = response.data.data.activity;
    // Transform backend response to frontend format
    return {
      ...activity,
      timestamp: activity.startedAt,
      data: activity.metadata,
    };
  },

  // Create a new activity
  createActivity: async (childId: string, data: CreateActivityData): Promise<Activity> => {
    // Transform frontend data structure to backend DTO format
    const payload: any = {
      type: data.type,
      startedAt: data.timestamp, // Backend expects startedAt, not timestamp
      metadata: data.data,        // Backend expects metadata, not data
      notes: data.notes,
    };

    // Extract endTime from metadata and set as endedAt (for sleep tracking)
    if (data.data?.endTime) {
      payload.endedAt = data.data.endTime;
    }

    const response = await apiClient.post(`/api/v1/activities?childId=${childId}`, payload);
    const activity = response.data.data.activity;
    // Transform backend response to frontend format
    return {
      ...activity,
      timestamp: activity.startedAt,
      data: activity.metadata,
    };
  },

  // Update an activity
  updateActivity: async (id: string, data: UpdateActivityData): Promise<Activity> => {
    const response = await apiClient.patch(`/api/v1/activities/${id}`, data);
    return response.data.data.activity;
  },

  // Delete an activity
  deleteActivity: async (id: string): Promise<void> => {
    await apiClient.delete(`/api/v1/activities/${id}`);
  },

  // Get daily summary
  getDailySummary: async (childId: string, date: string): Promise<DailySummary> => {
    const response = await apiClient.get('/api/v1/activities/daily-summary', {
      params: { childId, date },
    });
    return response.data.data;
  },
};
