import { httpClient } from '@/widgets/tasks/http/HttpClient'
import { Task } from '@/widgets/tasks/types/Task'
import { LoadTasksPayload } from '@/widgets/tasks/http/dto/LoadTasksPayload'
import { CreateTaskDto } from '@/widgets/tasks/http/dto/CreateTaskDto'
import { CreateNoteDto } from '@/widgets/tasks/http/dto/CreateNoteDto'
import { UpdateTaskDto } from '@/widgets/tasks/http/dto/UpdateTaskDto'
import { AddCommentDto } from '@/widgets/tasks/http/dto/AddCommentDto'
import { LoadTasksResponse } from '@/widgets/tasks/http/dto/LoadTasksResponse'

class TaskService {
  loadTasks(payload: LoadTasksPayload): Promise<LoadTasksResponse> {
    return httpClient.post('task/list', payload).then(response => response.data)
  }

  createTask(dto: CreateTaskDto | CreateNoteDto): Promise<Task> {
    const formData = this.createFormData(dto)

    return httpClient
      .post('task/create', formData)
      .then(response => response.data)
  }

  updateTaskDto(dto: UpdateTaskDto): Promise<Task> {
    const formData = this.createFormData(dto)

    return httpClient
      .post(`task/${dto.id}/update`, formData)
      .then(response => response.data)
  }

  removeTask(taskId: number): Promise<unknown> {
    return httpClient.post(`task/${taskId}/delete-undelete`)
  }

  toggleStatus(taskId: number): Promise<Task> {
    return httpClient
      .post(`task/${taskId}/change-status`)
      .then(response => response.data)
  }

  addComment(dto: AddCommentDto): Promise<Task> {
    return httpClient
      .post(`task/${dto.taskId}/message-add`, {
        text: dto.comment,
      })
      .then(response => response.data)
  }

  private createFormData(dto: UpdateTaskDto | CreateNoteDto | CreateTaskDto) {
    const formData = new FormData()

    Object.entries(dto).forEach(([fieldName, value]) => {
      if (!['files', 'candidateUids'].includes(fieldName)) {
        if (value !== null && value !== undefined) {
          formData.append(fieldName, value)
        }
      } else {
        ;(value as File[] | string[]).forEach((rowValue: File | string) => {
          formData.append(`${fieldName}[]`, rowValue)
        })
      }
    })

    return formData
  }
}

export default new TaskService()
