import { axiosClient } from '@/api/axiosClient'
import { isAxiosError } from 'axios'
import type { ReactivateChargeableCharConfigResponse } from '../types'

export type ReactivationNotAllowedReason =
  | 'ALREADY_ACTIVE'
  | 'VIGENTE_EXISTS'
  | 'POSTERIOR_ROWS_EXIST'

export class ReactivationNotAllowedError extends Error {
  reason: ReactivationNotAllowedReason

  constructor(reason: ReactivationNotAllowedReason, message: string) {
    super(message)
    this.name = 'ReactivationNotAllowedError'
    this.reason = reason
  }
}

export async function reactivateChargeableCharConfig(
  id: number,
): Promise<ReactivateChargeableCharConfigResponse> {
  try {
    const response = await axiosClient.patch<ReactivateChargeableCharConfigResponse>(
      `/api/v1/admin/chargeable-chars/${id}/reactivate`,
    )
    return response.data
  } catch (err) {
    if (
      isAxiosError(err) &&
      err.response?.status === 409 &&
      err.response.data?.code === 'CHARGEABLE_CHAR_REACTIVATION_NOT_ALLOWED'
    ) {
      const reason: ReactivationNotAllowedReason = err.response.data?.reason ?? 'ALREADY_ACTIVE'
      const message: string = err.response.data?.message ?? 'Reactivación no permitida.'
      throw new ReactivationNotAllowedError(reason, message)
    }
    throw err
  }
}
