import request from './request'
import type {
  ServiceGuideDetailResponse,
  ServiceGuideListParams,
  ServiceGuideListResponse,
} from '@/types/service-guide'

const BASE = '/api/v1/service-guides'

export function listServiceGuides(
  params: ServiceGuideListParams,
): Promise<ServiceGuideListResponse> {
  return request
    .get<ServiceGuideListResponse>(BASE, { params })
    .then((res) => res.data)
}

export function listServiceGuidesByMatter(
  matterId: string,
  page = 1,
  pageSize = 20,
): Promise<ServiceGuideListResponse> {
  return request
    .get<ServiceGuideListResponse>(`${BASE}/by-matter/${matterId}`, {
      params: { page, page_size: pageSize },
    })
    .then((res) => res.data)
}

export function getServiceGuideDetail(
  profileId: string,
): Promise<ServiceGuideDetailResponse> {
  return request
    .get<ServiceGuideDetailResponse>(`${BASE}/${profileId}`)
    .then((res) => res.data)
}

export function getServiceGuideByDoc(
  docId: string,
): Promise<ServiceGuideDetailResponse> {
  return request
    .get<ServiceGuideDetailResponse>(`${BASE}/by-doc/${docId}`)
    .then((res) => res.data)
}

export function findServiceGuideByDoc(
  docId: string,
): Promise<ServiceGuideDetailResponse | null> {
  return request
    .get<ServiceGuideDetailResponse | { detail?: string }>(`${BASE}/by-doc/${docId}`, {
      validateStatus: (status) => status < 500,
    })
    .then((res) => {
      if (res.status === 404) {
        return null
      }
      return res.data as ServiceGuideDetailResponse
    })
}