/**
 * Inventory (parity with CI `Views/inventory/*.php`).
 * Base: `/api/v1/administrator/inventory` with JWT unless noted.
 */
import { apiFetch } from './http'

const BASE = '/api/v1/inventory'

function q(searchParams: URLSearchParams): string {
  const s = searchParams.toString()
  return s ? `?${s}` : ''
}

export type InventoryKind = 'book' | 'classroom' | 'kitchen' | 'office'

/** Index list: expect `{ items, categories, userNames }` (names optional). */
export async function fetchInventoryIndex(
  kind: InventoryKind,
  searchParams: URLSearchParams,
): Promise<unknown> {
  const params = new URLSearchParams(searchParams)
  params.set('type', kind)
  return apiFetch(`${BASE}/items?${params.toString()}`)
}

export async function postInventoryCategory(body: Record<string, unknown>): Promise<unknown> {
  return apiFetch(`${BASE}/category`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export async function fetchInventoryItem(itemId: string | number): Promise<{
  item?: Record<string, unknown>
  categories?: Record<string, unknown>[]
  conditionOptions?: Record<string, string>
  [key: string]: unknown
}> {
  return apiFetch(`${BASE}/items/${itemId}`)
}

/** Create form payload (categories, defaults). */
export async function fetchInventoryCreateForm(
  kind: InventoryKind,
  searchParams: URLSearchParams,
): Promise<unknown> {
  return apiFetch(`${BASE}/${kind}/create${q(searchParams)}`)
}

export async function postInventoryItem(body: Record<string, unknown>): Promise<unknown> {
  return apiFetch(`${BASE}/items`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export async function putInventoryItem(
  itemId: string | number,
  body: Record<string, unknown>,
): Promise<unknown> {
  return apiFetch(`${BASE}/items/${itemId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export async function deleteInventoryItem(itemId: string | number): Promise<unknown> {
  return apiFetch(`${BASE}/items/${itemId}`, { method: 'DELETE' })
}

export async function postInventoryAdjust(
  itemId: string | number,
  body: Record<string, unknown>,
): Promise<unknown> {
  return apiFetch(`${BASE}/items/${itemId}/adjust`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export async function postClassroomAudit(
  itemId: string | number,
  body: Record<string, unknown>,
): Promise<unknown> {
  return apiFetch(`${BASE}/items/${itemId}/classroom-audit`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export async function fetchInventorySummary(searchParams: URLSearchParams): Promise<unknown> {
  const type = searchParams.get('type') || 'classroom'
  const params = new URLSearchParams(searchParams)
  params.delete('type')
  const qs = params.toString()
  return apiFetch(`${BASE}/summary/${type}${qs ? `?${qs}` : ''}`)
}

export async function fetchMovements(searchParams: URLSearchParams): Promise<unknown> {
  return apiFetch(`${BASE}/movements${q(searchParams)}`)
}

export async function fetchMovementForm(
  movementId: string | number | undefined,
  searchParams: URLSearchParams,
): Promise<unknown> {
  if (movementId === undefined || movementId === '') {
    return apiFetch(`${BASE}/movements/create${q(searchParams)}`)
  }
  return apiFetch(`${BASE}/movements/${movementId}/edit${q(searchParams)}`)
}

export async function postMovement(body: Record<string, unknown>): Promise<unknown> {
  return apiFetch(`${BASE}/movements`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export async function putMovement(
  movementId: string | number,
  body: Record<string, unknown>,
): Promise<unknown> {
  return apiFetch(`${BASE}/movements/${movementId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export async function deleteMovement(movementId: string | number): Promise<unknown> {
  return apiFetch(`${BASE}/movements/${movementId}`, { method: 'DELETE' })
}

export async function postMovementsBulkDelete(ids: number[]): Promise<unknown> {
  return apiFetch(`${BASE}/movements/bulk-delete`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ids }),
  })
}

/** Teacher book distribution — JWT; base matches CI `inventory/books/distribute`. */
const TEACHER_DIST = '/api/v1/teacher/inventory/books/distribute'

export async function fetchTeacherBookDistribute(
  searchParams: URLSearchParams,
): Promise<unknown> {
  return apiFetch(`${TEACHER_DIST}${q(searchParams)}`)
}

export async function postTeacherBookDistribute(body: Record<string, unknown>): Promise<unknown> {
  return apiFetch(TEACHER_DIST, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

/* ─── New Inventory Improvement API Calls ─── */

/** Fetch low-stock items (quantity <= reorder_point). */
export async function fetchLowStock(): Promise<unknown> {
  return apiFetch(`${BASE}/low-stock`)
}

/** Fetch reorder suggestions for low-stock items. */
export async function fetchReorderSuggestions(): Promise<unknown> {
  return apiFetch(`${BASE}/reorder-suggestions`)
}

/** Fetch stock status for all items (ok/low_stock/out_of_stock). */
export async function fetchStockStatus(
  searchParams: URLSearchParams,
): Promise<unknown> {
  return apiFetch(`${BASE}/stock-status${q(searchParams)}`)
}

/** Fetch inventory dashboard summary counts. */
export async function fetchInventoryDashboard(
  searchParams: URLSearchParams,
): Promise<unknown> {
  return apiFetch(`${BASE}/dashboard${q(searchParams)}`)
}

/** Void a movement (append-only correction with reverse entry). */
export async function voidMovement(
  movementId: string | number,
  reason: string,
): Promise<unknown> {
  return apiFetch(`${BASE}/movements/${movementId}/void`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ reason }),
  })
}

/** Create a correction movement linked to an existing movement. */
export async function correctMovement(
  movementId: string | number,
  qtyChange: number,
  reason: string,
): Promise<unknown> {
  return apiFetch(`${BASE}/movements/${movementId}/correct`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ qty_change: qtyChange, reason }),
  })
}
