import { db, mealPlans, mealPlanMembers, eq, and } from "@epicure/db";

export type MealPlanRole = "owner" | "editor" | "viewer";

export type MealPlanAccess = {
  plan: typeof mealPlans.$inferSelect;
  role: MealPlanRole;
};

/** Resolves a user's access to a meal plan by its id — owner, or member with their assigned role. Null if no access. */
export async function getMealPlanAccessById(
  mealPlanId: string,
  userId: string
): Promise<MealPlanAccess | null> {
  const plan = await db.query.mealPlans.findFirst({ where: eq(mealPlans.id, mealPlanId) });
  if (!plan) return null;
  if (plan.userId === userId) return { plan, role: "owner" };

  const member = await db.query.mealPlanMembers.findFirst({
    where: and(eq(mealPlanMembers.mealPlanId, mealPlanId), eq(mealPlanMembers.userId, userId)),
  });
  if (!member) return null;

  return { plan, role: member.role };
}

export function canWriteMealPlan(role: MealPlanRole): boolean {
  return role === "owner" || role === "editor";
}
