import apiClient from './client'

export interface TagResponse {
  id: number
  tag_name: string
  created_date: string
}

export interface TagsResponse {
  items: TagResponse[]
  total: number
}

export interface PhotoTagsRequest {
  photo_ids: number[]
  tag_names: string[]
}

export interface PhotoTagsResponse {
  message: string
  photos_updated: number
  tags_added: number
  tags_removed: number
}

export interface PhotoTagItem {
  tag_id: number
  tag_name: string
}

export interface PhotoTagsListResponse {
  photo_id: number
  tags: PhotoTagItem[]
  total: number
}

export interface TagUpdateRequest {
  tag_name: string
}

export interface TagDeleteRequest {
  tag_ids: number[]
}

export interface PhotoWithTagsItem {
  id: number
  filename: string
  path: string
  processed: boolean
  date_taken?: string | null
  date_added?: string | null
  face_count: number
  unidentified_face_count: number  // Count of faces with person_id IS NULL
  tags: string  // Comma-separated tags string
  people_names: string  // Comma-separated people names string
  media_type?: string | null  // 'image' or 'video'
}

export interface PhotosWithTagsResponse {
  items: PhotoWithTagsItem[]
  total: number
}

export const tagsApi = {
  list: async (): Promise<TagsResponse> => {
    const { data } = await apiClient.get<TagsResponse>('/api/v1/tags')
    return data
  },

  create: async (tagName: string): Promise<TagResponse> => {
    const { data } = await apiClient.post<TagResponse>('/api/v1/tags', {
      tag_name: tagName,
    })
    return data
  },

  addToPhotos: async (request: PhotoTagsRequest): Promise<PhotoTagsResponse> => {
    const { data } = await apiClient.post<PhotoTagsResponse>(
      '/api/v1/tags/photos/add',
      request
    )
    return data
  },

  removeFromPhotos: async (request: PhotoTagsRequest): Promise<PhotoTagsResponse> => {
    const { data } = await apiClient.post<PhotoTagsResponse>(
      '/api/v1/tags/photos/remove',
      request
    )
    return data
  },
  getPhotoTags: async (photoId: number): Promise<PhotoTagsListResponse> => {
    const { data } = await apiClient.get<PhotoTagsListResponse>(
      `/api/v1/tags/photos/${photoId}`
    )
    return data
  },
  update: async (tagId: number, tagName: string): Promise<TagResponse> => {
    const { data } = await apiClient.put<TagResponse>(`/api/v1/tags/${tagId}`, {
      tag_name: tagName,
    })
    return data
  },
  delete: async (tagIds: number[]): Promise<{ message: string; deleted_count: number }> => {
    const { data } = await apiClient.post<{ message: string; deleted_count: number }>(
      '/api/v1/tags/delete',
      { tag_ids: tagIds }
    )
    return data
  },
  getPhotosWithTags: async (): Promise<PhotosWithTagsResponse> => {
    const { data } = await apiClient.get<PhotosWithTagsResponse>('/api/v1/tags/photos')
    return data
  },
}

export default tagsApi

