// src/server/features/reference_books/lib/inventory.workflow.ts
// Approval workflow logic for inventory entries

import { db } from '../../../shared/db/client';
import { inventoryTable, inventoryPendingTable } from '../db/inventory.table';
import { eq } from 'drizzle-orm';
import { logger } from '../../../shared/lib/logger';
import { executeApproveInventory, executeRejectInventory } from './inventory.core';
import type { InventoryPending } from '../db/inventory.table';

// Type for inventory entry
type InventoryEntry = typeof inventoryTable.$inferSelect;

/**
 * Approve inventory entry (Admin only)
 * Updates original entry and deletes pending entry
 */
export async function approveInventoryEntry(targetId: string, reviewerId: string): Promise<InventoryEntry> {
  logger.info(`[Inventory] Approving entry: ${targetId} by reviewer: ${reviewerId}`);
  return await executeApproveInventory(targetId, reviewerId);
}

/**
 * Reject inventory entry (Admin only)
 */
export async function rejectInventoryEntry(targetId: string, reason: string, reviewerId: string): Promise<void> {
  logger.info(`[Inventory] Rejecting entry: ${targetId} with reason: ${reason} by reviewer: ${reviewerId}`);
  return await executeRejectInventory(targetId, reason, reviewerId);
}

/**
 * Get pending inventory entries
 */
export async function getPendingInventoryEntries(): Promise<InventoryPending[]> {
  const entries = await db.select()
    .from(inventoryPendingTable)
    .where(eq(inventoryPendingTable.status, 'pending'))
    .orderBy(inventoryPendingTable.createdAt);

  return entries;
}

/**
 * Get pending inventory entries by targetId
 */
export async function getPendingInventoryEntryByTargetId(targetId: string): Promise<InventoryPending | null> {
  const entries = await db.select()
    .from(inventoryPendingTable)
    .where(eq(inventoryPendingTable.targetId, targetId))
    .limit(1);

  return entries[0] || null;
}
