import { api } from './api'
import type { Chore, ChoreCreate, ChoreUpdate, ChoreType, ChoreAssignment, ChoreAssignmentCreate, ChoreAssignmentUpdate, ChoreHistory } from '../types/chore'
import { groupService } from './groupService'
import type { Group } from './groupService'
import { apiClient, API_ENDPOINTS } from '@/config/api'

export const choreService = {
  async getAllChores(): Promise<Chore[]> {
    try {
      // Use the new optimized endpoint that returns all chores in a single request
      const response = await api.get('/api/v1/chores/all')
      return response.data
    } catch (error) {
      console.error('Failed to get all chores via optimized endpoint, falling back to individual calls:', error)
      // Fallback to the original method if the new endpoint fails
      return this.getAllChoresFallback()
    }
  },

  // Fallback method using individual API calls (kept for compatibility)
  async getAllChoresFallback(): Promise<Chore[]> {
    let allChores: Chore[] = []
    try {
      const personalChores = await this.getPersonalChores()
      allChores = allChores.concat(personalChores)

      // Fetch chores for all groups
      const userGroups: Group[] = await groupService.getUserGroups()
      for (const group of userGroups) {
        try {
          const groupChores = await this.getChores(group.id)
          allChores = allChores.concat(groupChores)
        } catch (groupError) {
          console.error(`Failed to get chores for group ${group.id} (${group.name}):`, groupError)
          // Continue fetching chores for other groups
        }
      }
    } catch (error) {
      console.error('Failed to get all chores:', error)
      // Optionally re-throw or handle as per application's error strategy
      throw error
    }
    return allChores
  },

  // Group Chores (specific fetch, might still be used internally or for specific group views)
  async getChores(groupId: number): Promise<Chore[]> {
    const response = await api.get(`/api/v1/chores/groups/${groupId}/chores`)
    return response.data
  },

  // Unified createChore
  async createChore(chore: ChoreCreate): Promise<Chore> {
    if (chore.type === 'personal') {
      const response = await api.post('/api/v1/chores/personal', chore)
      return response.data
    } else if (chore.type === 'group' && chore.group_id) {
      const response = await api.post(`/api/v1/chores/groups/${chore.group_id}/chores`, chore)
      return response.data
    } else {
      throw new Error('Invalid chore type or missing group_id for group chore')
    }
  },

  // Unified updateChore
  async updateChore(choreId: number, chore: ChoreUpdate): Promise<Chore> {
    if (chore.type === 'personal') {
      // For personal chores, group_id is not part of the route
      const response = await api.put(`/api/v1/chores/personal/${choreId}`, chore)
      return response.data
    } else if (chore.type === 'group' && chore.group_id) {
      const response = await api.put(
        `/api/v1/chores/groups/${chore.group_id}/chores/${choreId}`,
        chore,
      )
      return response.data
    } else {
      throw new Error('Invalid chore type or missing group_id for group chore update')
    }
  },

  // Unified deleteChore
  async deleteChore(choreId: number, choreType: ChoreType, groupId?: number): Promise<void> {
    if (choreType === 'personal') {
      await api.delete(`/api/v1/chores/personal/${choreId}`)
    } else if (choreType === 'group' && groupId) {
      await api.delete(`/api/v1/chores/groups/${groupId}/chores/${choreId}`)
    } else {
      throw new Error('Invalid chore type or missing group_id for group chore deletion')
    }
  },

  // Personal Chores (specific fetch, used by getAllChores)
  async getPersonalChores(): Promise<Chore[]> {
    const response = await api.get('/api/v1/chores/personal')
    return response.data
  },

  // === CHORE ASSIGNMENT METHODS ===

  // Create chore assignment
  async createAssignment(assignment: ChoreAssignmentCreate): Promise<ChoreAssignment> {
    const response = await api.post('/api/v1/chores/assignments', assignment)
    return response.data
  },

  // Get user's assignments
  async getMyAssignments(includeCompleted: boolean = false): Promise<ChoreAssignment[]> {
    const response = await api.get(`/api/v1/chores/assignments/my?include_completed=${includeCompleted}`)
    return response.data
  },

  // Get assignments for a specific chore
  async getChoreAssignments(choreId: number): Promise<ChoreAssignment[]> {
    const response = await api.get(`/api/v1/chores/chores/${choreId}/assignments`)
    return response.data
  },

  // Update assignment
  async updateAssignment(assignmentId: number, update: ChoreAssignmentUpdate): Promise<ChoreAssignment> {
    const response = await apiClient.put(`/api/v1/chores/assignments/${assignmentId}`, update)
    return response.data
  },

  // Delete assignment
  async deleteAssignment(assignmentId: number): Promise<void> {
    await api.delete(`/api/v1/chores/assignments/${assignmentId}`)
  },

  // Mark assignment as complete (convenience method)
  async completeAssignment(assignmentId: number): Promise<ChoreAssignment> {
    const response = await api.patch(`/api/v1/chores/assignments/${assignmentId}/complete`)
    return response.data
  },

  // Removed createPersonalChore, updatePersonalChore, deletePersonalChore
  // They are merged into the unified methods above.

  // Original group-specific methods might be kept if there are pages
  // that specifically deal ONLY with a single group's chores and pass groupId.
  // For ChoresPage.vue, we'll use the unified methods.

  // The original group chore methods are below, we can decide to remove them if
  // the unified methods cover all use cases and no other part of the app uses them directly.

  // async createChore(groupId: number, chore: ChoreCreate): Promise<Chore> { // Original group create
  //   const response = await api.post(`/api/v1/chores/groups/${groupId}/chores`, chore)
  //   return response.data
  // },

  async _original_updateGroupChore(
    groupId: number,
    choreId: number,
    chore: ChoreUpdate,
  ): Promise<Chore> {
    // Renamed original
    const response = await api.put(`/api/v1/chores/groups/${groupId}/chores/${choreId}`, chore)
    return response.data
  },

  async _original_deleteGroupChore(groupId: number, choreId: number): Promise<void> {
    // Renamed original
    await api.delete(`/api/v1/chores/groups/${groupId}/chores/${choreId}`)
  },

  // Personal Chores (getPersonalChores is kept as it's used by getAllChores)
  // async getPersonalChores(): Promise<Chore[]> { ... }

  // async createPersonalChore(chore: ChoreCreate): Promise<Chore> { // Removed
  //   const response = await api.post('/api/v1/chores/personal', chore)
  //   return response.data
  // },

  async _updatePersonalChore(choreId: number, chore: ChoreUpdate): Promise<Chore> {
    // Renamed original for safety, to be removed
    const response = await api.put(`/api/v1/chores/personal/${choreId}`, chore)
    return response.data
  },

  async _deletePersonalChore(choreId: number): Promise<void> {
    // Renamed original for safety, to be removed
    await api.delete(`/api/v1/chores/personal/${choreId}`)
  },

  async getChoreHistory(choreId: number): Promise<ChoreHistory[]> {
    const response = await apiClient.get(API_ENDPOINTS.CHORES.HISTORY(choreId))
    return response.data
  },
}
