File size: 5,633 Bytes
5883557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { getSession } from 'next-auth/react'

class APIClient {
  private client: AxiosInstance
  private baseURL: string

  constructor() {
    this.baseURL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
    
    this.client = axios.create({
      baseURL: this.baseURL,
      timeout: 30000,
      headers: {
        'Content-Type': 'application/json',
      },
    })

    // Request interceptor for auth
    this.client.interceptors.request.use(
      async (config) => {
        const session = await getSession()
        if (session?.accessToken) {
          config.headers.Authorization = `Bearer ${session.accessToken}`
        }
        return config
      },
      (error) => Promise.reject(error)
    )

    // Response interceptor for error handling
    this.client.interceptors.response.use(
      (response) => response,
      async (error) => {
        if (error.response?.status === 401) {
          // Handle token refresh or redirect to login
          window.location.href = '/login'
        }
        return Promise.reject(error)
      }
    )
  }

  // Generic request method
  async request<T>(config: AxiosRequestConfig): Promise<T> {
    const response = await this.client.request<T>(config)
    return response.data
  }

  // Convenience methods
  async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'GET', url })
  }

  async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'POST', url, data })
  }

  async put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'PUT', url, data })
  }

  async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE', url })
  }

  // File upload
  async upload<T>(
    url: string,
    file: File,
    onProgress?: (progress: number) => void
  ): Promise<T> {
    const formData = new FormData()
    formData.append('file', file)

    return this.request<T>({
      method: 'POST',
      url,
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress && progressEvent.total) {
          const progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          onProgress(progress)
        }
      },
    })
  }

  // WebSocket connection for real-time updates
  createWebSocket(path: string): WebSocket {
    const wsURL = this.baseURL.replace(/^http/, 'ws')
    return new WebSocket(`${wsURL}${path}`)
  }
}

// Export singleton instance
export const apiClient = new APIClient()

// Export typed API methods
export const api = {
  // Auth
  auth: {
    login: (credentials: { email: string; password: string }) =>
      apiClient.post<{ token: string; user: any }>('/auth/login', credentials),
    
    register: (data: { email: string; password: string; name: string }) =>
      apiClient.post<{ token: string; user: any }>('/auth/register', data),
    
    logout: () => apiClient.post('/auth/logout'),
    
    refreshToken: () =>
      apiClient.post<{ token: string }>('/auth/refresh'),
  },

  // Processing
  processing: {
    removeBackground: (file: File, options?: any, onProgress?: (p: number) => void) =>
      apiClient.upload<{ id: string; result: string }>('/process/remove-background', file, onProgress),
    
    replaceBackground: (imageId: string, backgroundId: string) =>
      apiClient.post<{ result: string }>('/process/replace-background', {
        imageId,
        backgroundId,
      }),
    
    batchProcess: (files: File[], options?: any) => {
      const formData = new FormData()
      files.forEach((file) => formData.append('files', file))
      if (options) {
        formData.append('options', JSON.stringify(options))
      }
      return apiClient.post<{ jobId: string }>('/process/batch', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
    },
    
    getJobStatus: (jobId: string) =>
      apiClient.get<{ status: string; progress: number; results?: any[] }>(
        `/process/jobs/${jobId}`
      ),
  },

  // Projects
  projects: {
    list: (params?: { page?: number; limit?: number; search?: string }) =>
      apiClient.get<{ items: any[]; total: number }>('/projects', { params }),
    
    get: (id: string) =>
      apiClient.get<any>(`/projects/${id}`),
    
    create: (data: any) =>
      apiClient.post<any>('/projects', data),
    
    update: (id: string, data: any) =>
      apiClient.put<any>(`/projects/${id}`, data),
    
    delete: (id: string) =>
      apiClient.delete(`/projects/${id}`),
  },

  // Backgrounds
  backgrounds: {
    list: (category?: string) =>
      apiClient.get<any[]>('/backgrounds', { params: { category } }),
    
    upload: (file: File) =>
      apiClient.upload<{ id: string; url: string }>('/backgrounds/upload', file),
    
    generate: (prompt: string) =>
      apiClient.post<{ id: string; url: string }>('/backgrounds/generate', { prompt }),
  },

  // User
  user: {
    profile: () =>
      apiClient.get<any>('/user/profile'),
    
    updateProfile: (data: any) =>
      apiClient.put<any>('/user/profile', data),
    
    usage: () =>
      apiClient.get<{ images: number; videos: number; storage: number }>(
        '/user/usage'
      ),
    
    billing: () =>
      apiClient.get<any>('/user/billing'),
  },
}

export default api