/**
 * Vendor recommendations queries — list and dismiss AI-generated recommendations.
 *
 * Recommendations are generated nightly by the vendorRecommendationsCron job
 * and cached in the vendor_recommendations table. Dashboard reads latest
 * non-dismissed rows.
 */

import { and, desc, eq, isNull } from 'drizzle-orm';
import type { DrizzleClient } from '../client.js';
import { vendorRecommendations } from '../schema.js';

export type VendorRecommendation = typeof vendorRecommendations.$inferSelect;

export type VendorRecommendationKind =
  | 'stock_nudge'
  | 'pricing_suggestion'
  | 'schedule_opportunity';

/**
 * List latest non-dismissed recommendations for a vendor.
 *
 * Returns at most `limit` rows ordered newest-first.
 * Default limit: 3 (dashboard shows top 3 only).
 */
export async function listLatestForVendor(
  db: DrizzleClient,
  vendorId: string,
  limit = 3,
): Promise<VendorRecommendation[]> {
  return db
    .select()
    .from(vendorRecommendations)
    .where(
      and(eq(vendorRecommendations.vendorId, vendorId), isNull(vendorRecommendations.dismissedAt)),
    )
    .orderBy(desc(vendorRecommendations.createdAt))
    .limit(limit);
}

/**
 * Mark a recommendation as dismissed.
 *
 * Idempotent: if already dismissed, updates dismissedAt to now (re-dismiss).
 */
export async function dismissRecommendation(
  db: DrizzleClient,
  recommendationId: string,
  vendorId: string,
): Promise<void> {
  await db
    .update(vendorRecommendations)
    .set({ dismissedAt: new Date() })
    .where(
      and(
        eq(vendorRecommendations.id, recommendationId),
        eq(vendorRecommendations.vendorId, vendorId),
      ),
    );
}

/**
 * Insert new recommendation rows for a vendor.
 *
 * Called by the nightly cron after generating fresh recommendations.
 * Returns inserted row IDs.
 */
export async function insertRecommendations(
  db: DrizzleClient,
  rows: Array<{
    vendorId: string;
    kind: VendorRecommendationKind;
    payload: Record<string, unknown>;
  }>,
): Promise<string[]> {
  if (rows.length === 0) return [];
  const inserted = await db
    .insert(vendorRecommendations)
    .values(rows)
    .returning({ id: vendorRecommendations.id });
  return inserted.map((r) => r.id);
}
