import { apiClient } from '@/services/api/client';
import { Post, Notification, Comment } from '../types';
import { BackendPost, BackendFeedItem } from '../types/backend-types';
import { UserProfile } from '../features/profile/services/profileService';

export const socialService = {
  getFeed: async (params?: { page?: number; limit?: number }) => {
    const response = await apiClient.get<BackendFeedItem[]>('/social/feed', {
      params,
    });
    // Map BackendFeedItem to Post
    const posts: Post[] = response.data.map((item) => ({
      id: item.id,
      author: {
        name: 'User', // Placeholder
        handle: '@user', // Placeholder
        avatar: '', // Placeholder
      },
      content: item.content,
      timestamp: item.created_at,
      likes: 0, // FeedItem doesn't have likes count yet
      comments: 0,
      shares: 0,
      type: 'text', // Default
    }));
    return { posts };
  },

  getPostsByUser: async (userId: string, page = 1, profile?: UserProfile) => {
    const response = await apiClient.get<BackendPost[]>(
      `/social/posts/user/${userId}`,
      {
        params: { page, limit: 10 },
      },
    );

    const author = profile
      ? {
          name:
            profile.first_name || profile.last_name
              ? `${profile.first_name || ''} ${profile.last_name || ''}`.trim()
              : profile.username,
          handle: `@${profile.username}`,
          avatar: profile.avatar_url || '',
          isVerified: false, // Not in profile yet
        }
      : {
          name: 'User',
          handle: '@user',
          avatar: '',
        };

    const posts: Post[] = response.data.map((p) => ({
      id: p.id,
      author,
      content: p.content,
      timestamp: p.created_at,
      likes: p.like_count,
      comments: p.comment_count,
      shares: 0,
      type: 'text', // Backend doesn't differentiate richly yet, usually text + attachments
      // We could check p.track_id to set type='audio'
    }));

    return { posts, total: 100 }; // Mock total for now as backend doesn't return pagination metadata
  },

  createPost: async (data: {
    content: string;
    attachments?: Record<string, string>;
  }) => {
    const response = await apiClient.post<BackendPost>('/social/posts', data);
    const p = response.data;
    // Return a Post object
    return {
      post: {
        id: p.id,
        author: { name: 'Me', handle: '@me', avatar: '' }, // Optimistic update will fix this or caller handles it
        content: p.content,
        timestamp: p.created_at,
        likes: 0,
        comments: 0,
        shares: 0,
        type: 'text',
      } as Post,
    };
  },

  toggleLike: async (
    targetId: string,
    targetType: 'post' | 'track' | 'playlist',
  ) => {
    const response = await apiClient.post<{ liked: boolean }>('/social/like', {
      target_id: targetId,
      target_type: targetType,
    });
    return response.data;
  },

  getChatToken: async () => {
    const response = await apiClient.post<{ token: string }>('/chat/token');
    return response.data;
  },

  getChatStats: async () => {
    const response = await apiClient.get('/chat/stats');
    return response.data;
  },

  getComments: async (trackId: string) => {
    const response = await apiClient.get(`/tracks/${trackId}/comments`);
    return { comments: response.data };
  },

  postComment: async (trackId: string, content: string) => {
    const response = await apiClient.post(`/tracks/${trackId}/comments`, {
      content,
    });
    return response.data;
  },

  deleteComment: async (id: string) => {
    await apiClient.delete(`/comments/${id}`);
  },

  getNotifications: async () => {
    const response = await apiClient.get('/notifications');
    return { notifications: response.data };
  },

  markRead: async (id: string) => {
    await apiClient.post(`/notifications/${id}/read`);
  },

  markAllRead: async () => {
    await apiClient.post('/notifications/read-all');
  },

  getWebhooks: async () => {
    const response = await apiClient.get('/webhooks');
    return response.data;
  },

  registerWebhook: async (data: any) => {
    await apiClient.post('/webhooks', data);
  },

  deleteWebhook: async (id: string) => {
    await apiClient.delete(`/webhooks/${id}`);
  },

  testWebhook: async (id: string) => {
    await apiClient.post(`/webhooks/${id}/test`);
  },

  getWebhookStats: async () => {
    const response = await apiClient.get('/webhooks/stats');
    return response.data;
  },

  regenerateWebhookKey: async (id: string) => {
    const response = await apiClient.post<{ api_key: string }>(
      `/webhooks/${id}/regenerate-key`,
    );
    return response.data;
  },
};
