import { getFilteredJobs, getFiltersFromJobs } from "./utils"

import {
  type Action,
  ActionType,
  type InitState,
  type State,
} from "@/types/components/blocks/jobylonFeed"

export function init(initState: InitState): State {
  const { country, city, department, category } = getFiltersFromJobs(
    initState.allJobs
  )

  return {
    allJobs: initState.allJobs,
    jobs: initState.allJobs,
    countryFilters: country,
    cityFilters: city,
    departmentFilters: department,
    categoryFilters: category,
    chosenCategoryFilter: "",
    chosenCityFilter: "",
    chosenCountryFilter: "",
    chosenDepartmentFilter: "",
  }
}

export function reducer(state: State, action: Action) {
  const type = action.type
  switch (type) {
    case ActionType.UPDATE_FILTER: {
      const filters = {
        country: state.chosenCountryFilter,
        city: state.chosenCityFilter,
        department: state.chosenDepartmentFilter,
        category: state.chosenCategoryFilter,
        [action.payload.filter]: action.payload.value,
      }
      const jobs = getFilteredJobs(state.allJobs, filters)
      const { country, city, department, category } = getFiltersFromJobs(jobs)

      return {
        ...state,
        chosenCountryFilter: filters.country,
        chosenCityFilter: filters.city,
        chosenDepartmentFilter: filters.department,
        chosenCategoryFilter: filters.category,
        countryFilters: country,
        cityFilters: city,
        departmentFilters: department,
        categoryFilters: category,
        jobs,
      }
    }
    default:
      const unhandledActionType: never = type
      console.info(`Unhandled type: ${unhandledActionType}`)
      return state
  }
}
