import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import type { RootState } from '../index';

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({
    baseUrl: 'http://localhost:8001/api',
    prepareHeaders: (headers, { getState }) => {
      const token = (getState() as RootState).auth.token;
      if (token) {
        headers.set('authorization', `Bearer ${token}`);
      }
      headers.set('Content-Type', 'application/json');
      return headers;
    },
  }),
  tagTypes: ['Token', 'Trade', 'Portfolio', 'News', 'Analysis', 'Signal', 'Subscription'],
  endpoints: (builder) => ({
    // Token endpoints
    getTokens: builder.query({
      query: (params = {}) => ({
        url: '/tokens',
        params,
      }),
      providesTags: ['Token'],
    }),
    getTrendingTokens: builder.query({
      query: () => '/tokens/trending',
      providesTags: ['Token'],
    }),
    getFeaturedTokens: builder.query({
      query: () => '/tokens/featured',
      providesTags: ['Token'],
    }),
    getToken: builder.query({
      query: (id) => `/tokens/${id}`,
      providesTags: (result, error, id) => [{ type: 'Token', id }],
    }),
    
    // Trade endpoints
    createTrade: builder.mutation({
      query: (tradeData) => ({
        url: '/trades',
        method: 'POST',
        body: tradeData,
      }),
      invalidatesTags: ['Trade', 'Portfolio'],
    }),
    getTrades: builder.query({
      query: (params = {}) => ({
        url: '/trades',
        params,
      }),
      providesTags: ['Trade'],
    }),
    
    // Portfolio endpoints
    getPortfolioHoldings: builder.query({
      query: () => '/portfolio/holdings',
      providesTags: ['Portfolio'],
    }),
    getPortfolioStats: builder.query({
      query: () => '/portfolio/stats',
      providesTags: ['Portfolio'],
    }),
    getPortfolioPerformance: builder.query({
      query: (timeframe) => `/portfolio/performance?timeframe=${timeframe}`,
      providesTags: ['Portfolio'],
    }),
    
    // News endpoints
    getNews: builder.query({
      query: (params = {}) => ({
        url: '/news',
        params,
      }),
      providesTags: ['News'],
    }),
    getFeaturedNews: builder.query({
      query: () => '/news/featured',
      providesTags: ['News'],
    }),
    
    // Analysis endpoints (Premium)
    getMarketAnalysis: builder.query({
      query: (params = {}) => ({
        url: '/market-analysis',
        params,
      }),
      providesTags: ['Analysis'],
    }),
    
    // Signals endpoints (Premium)
    getInsiderSignals: builder.query({
      query: (params = {}) => ({
        url: '/insider-signals',
        params,
      }),
      providesTags: ['Signal'],
    }),
    
    // Subscription endpoints
    getSubscriptionPackages: builder.query({
      query: () => '/subscriptions/packages',
      providesTags: ['Subscription'],
    }),
    getUserSubscription: builder.query({
      query: () => '/subscriptions/user',
      providesTags: ['Subscription'],
    }),
    subscribeToPlan: builder.mutation({
      query: (planData) => ({
        url: '/subscriptions/subscribe',
        method: 'POST',
        body: planData,
      }),
      invalidatesTags: ['Subscription'],
    }),
  }),
});

export const {
  useGetTokensQuery,
  useGetTrendingTokensQuery,
  useGetFeaturedTokensQuery,
  useGetTokenQuery,
  useCreateTradeMutation,
  useGetTradesQuery,
  useGetPortfolioHoldingsQuery,
  useGetPortfolioStatsQuery,
  useGetPortfolioPerformanceQuery,
  useGetNewsQuery,
  useGetFeaturedNewsQuery,
  useGetMarketAnalysisQuery,
  useGetInsiderSignalsQuery,
  useGetSubscriptionPackagesQuery,
  useGetUserSubscriptionQuery,
  useSubscribeToPlanMutation,
} = api; 