import { isValidObjectId } from "mongoose";
import Occasion from "../models/occasion";

/**
 * Validates an `occasion` value sent by a client when creating/updating an
 * event. Returns the id to store (`null` clears it), or an error message.
 *
 * - `undefined` → `{ id: undefined }` (field not sent; leave unchanged)
 * - `null` / `""` → `{ id: null }` (clear the occasion)
 * - an id → must exist and be active, unless it equals `currentId` (so an
 *   event can keep an occasion that was deactivated after it was picked)
 */
export const resolveOccasion = async (
  occasion: unknown,
  currentId?: string | null,
): Promise<{ id?: string | null; error?: string }> => {
  if (occasion === undefined) return { id: undefined };
  if (occasion === null || occasion === "") return { id: null };

  if (typeof occasion !== "string" || !isValidObjectId(occasion)) {
    return { error: "occasion is not valid" };
  }
  if (currentId && String(currentId) === occasion) return { id: occasion };

  try {
    const found = await Occasion.findOne({ _id: occasion, isActive: true });
    if (!found) return { error: "occasion not found or inactive" };
    return { id: occasion };
  } catch {
    return { error: "could not validate occasion" };
  }
};

/** Extracts the id from a populated or unpopulated occasion reference. */
export const occasionIdOf = (occasion: any): string | undefined =>
  occasion ? String(occasion._id ?? occasion) : undefined;
