import { api, type ApiEnvelope, unwrapApiData } from '@/lib/api'
import { type PageResult } from '@/features/admin/api'

export type SourceType = 'third_party' | 'self_owned'
export type FulfillmentType = 'third_party_api' | 'local_only' | 'manual'
export type OrderFormFieldType =
  | 'text'
  | 'password'
  | 'phone'
  | 'number'
  | 'textarea'
  | 'select'
  | 'checkbox'

export type OrderFormField = {
  key: string
  label: string
  type: OrderFormFieldType
  required: boolean
  placeholder: string | null
  options?: Array<{ label: string; value: string }>
}

export type CatalogCategory = {
  id: string
  sourceType: SourceType
  apiAccountId: string | null
  provider: string | null
  externalId: string | null
  remoteCategoryId: string | null
  name: string
  sortOrder: number
  enabled: boolean
  rawPayload: Record<string, unknown> | null
  lastSyncedAt: string | null
  createdAt: string
  updatedAt: string
}

export type CatalogProduct = {
  id: string
  sourceType: SourceType
  apiAccountId: string | null
  provider: string | null
  externalId: string | null
  categoryId: string | null
  categoryName: string | null
  categorySourceType: SourceType | null
  remoteCategoryId: string | null
  remoteCourseId: string | null
  name: string
  price: string
  coverUrl: string | null
  content: string | null
  stock: number | null
  salesLimit: number | null
  fulfillmentType: FulfillmentType
  afterSalesNote: string | null
  orderFormSchema: OrderFormField[] | null
  sortOrder: number
  isFavorite: boolean
  enabled: boolean
  syncStatus: 'active' | 'removed'
  rawPayload: Record<string, unknown> | null
  lastSyncedAt: string | null
  lastSeenAt: string | null
  lastSeenSyncJobId: string | null
  removedAt: string | null
  createdAt: string
  updatedAt: string
}

export type SyncResult = {
  provider: string
  jobId?: string
  triggerType?: 'manual' | 'scheduled'
  status?: 'running' | 'success' | 'failed'
  skipped?: boolean
  reason?: string
  categoryTotal?: number
  productTotal?: number
  categoryCreated?: number
  categoryUpdated?: number
  productCreated?: number
  productUpdated?: number
  productRemoved?: number
  startedAt?: string
  finishedAt?: string | null
}

export type CatalogSyncJob = {
  id: string
  provider: string
  triggerType: 'manual' | 'scheduled'
  status: 'running' | 'success' | 'failed'
  startedAt: string
  finishedAt: string | null
  categoryTotal: number
  productTotal: number
  categoryCreated: number
  categoryUpdated: number
  productCreated: number
  productUpdated: number
  productRemoved: number
  errorMessage: string | null
}

export type CategoryPayload = {
  name: string
  sortOrder: number
  enabled: boolean
}

export type ProductPayload = {
  categoryId: string | null
  name: string
  price: string
  coverUrl: string | null
  content: string | null
  stock: number | null
  salesLimit: number | null
  fulfillmentType: FulfillmentType
  afterSalesNote: string | null
  orderFormSchema: OrderFormField[] | null
  sortOrder: number
  enabled: boolean
}

export function listCatalogCategories(params: {
  page: number
  pageSize: number
  keyword?: string
  sourceType?: string
  enabled?: string
}) {
  return api
    .get<
      PageResult<CatalogCategory> | ApiEnvelope<PageResult<CatalogCategory>>
    >('/api/admin/catalog/categories', { params })
    .then((response) => unwrapApiData(response.data))
}

export function createCatalogCategory(data: CategoryPayload) {
  return api
    .post<CatalogCategory | ApiEnvelope<CatalogCategory>>(
      '/api/admin/catalog/categories',
      data
    )
    .then((response) => unwrapApiData(response.data))
}

export function updateCatalogCategory(id: string, data: CategoryPayload) {
  return api
    .patch<CatalogCategory | ApiEnvelope<CatalogCategory>>(
      `/api/admin/catalog/categories/${id}`,
      data
    )
    .then((response) => unwrapApiData(response.data))
}

export function updateCatalogCategoryEnabled(id: string, enabled: boolean) {
  return api
    .patch<CatalogCategory | ApiEnvelope<CatalogCategory>>(
      `/api/admin/catalog/categories/${id}/enabled`,
      { enabled }
    )
    .then((response) => unwrapApiData(response.data))
}

export function deleteCatalogCategory(id: string) {
  return api
    .delete<
      { id: string; deleted: boolean } | ApiEnvelope<{ id: string; deleted: boolean }>
    >(
      `/api/admin/catalog/categories/${id}`
    )
    .then((response) => unwrapApiData(response.data))
}

export function syncCatalogThirdPartyCategories() {
  return api
    .post<SyncResult | ApiEnvelope<SyncResult>>(
      '/api/admin/catalog/categories/sync-third-party'
    )
    .then((response) => unwrapApiData(response.data))
}

export function listCatalogSyncJobs(params: {
  page: number
  pageSize: number
}) {
  return api
    .get<PageResult<CatalogSyncJob> | ApiEnvelope<PageResult<CatalogSyncJob>>>(
      '/api/admin/catalog/sync-jobs',
      { params }
    )
    .then((response) => unwrapApiData(response.data))
}

export function listCatalogProducts(params: {
  page: number
  pageSize: number
  keyword?: string
  sourceType?: string
  enabled?: string
  categoryId?: string
  remoteCategoryId?: string
}) {
  return api
    .get<PageResult<CatalogProduct> | ApiEnvelope<PageResult<CatalogProduct>>>(
      '/api/admin/catalog/products',
      { params }
    )
    .then((response) => unwrapApiData(response.data))
}

export function createCatalogProduct(data: ProductPayload) {
  return api
    .post<CatalogProduct | ApiEnvelope<CatalogProduct>>(
      '/api/admin/catalog/products',
      data
    )
    .then((response) => unwrapApiData(response.data))
}

export function updateCatalogProduct(id: string, data: ProductPayload) {
  return api
    .patch<CatalogProduct | ApiEnvelope<CatalogProduct>>(
      `/api/admin/catalog/products/${id}`,
      data
    )
    .then((response) => unwrapApiData(response.data))
}

export function updateCatalogProductEnabled(id: string, enabled: boolean) {
  return api
    .patch<CatalogProduct | ApiEnvelope<CatalogProduct>>(
      `/api/admin/catalog/products/${id}/enabled`,
      { enabled }
    )
    .then((response) => unwrapApiData(response.data))
}

export function deleteCatalogProduct(id: string) {
  return api
    .delete<
      { id: string; deleted: boolean } | ApiEnvelope<{ id: string; deleted: boolean }>
    >(
      `/api/admin/catalog/products/${id}`
    )
    .then((response) => unwrapApiData(response.data))
}

export function syncCatalogThirdPartyProducts(remoteCategoryId?: string) {
  return api
    .post<SyncResult | ApiEnvelope<SyncResult>>(
      '/api/admin/catalog/products/sync-third-party',
      null,
      { params: { remoteCategoryId } }
    )
    .then((response) => unwrapApiData(response.data))
}
