import { PLAN_FEATURES } from "@haushaltsApp/shared/constants/plans";
import type { Context, MiddlewareHandler, Next } from "hono";
import { createMiddleware } from "hono/factory";

export type PlanVariables = {
  plan: keyof typeof PLAN_FEATURES;
};

export const planMiddleware: MiddlewareHandler<{ Variables: PlanVariables }> =
  createMiddleware(async (c: Context, next: Next) => {
    // TODO: Load from DB based on householdId
    // For now default to free plan
    c.set("plan", "free" as const);
    await next();
  });

export function requireFeature(feature: keyof (typeof PLAN_FEATURES)["pro"]): MiddlewareHandler {
  return createMiddleware(async (c: Context, next: Next) => {
    const plan = (c.get("plan") as keyof typeof PLAN_FEATURES) ?? "free";
    const features = PLAN_FEATURES[plan] as Record<string, unknown>;
    if (!features[feature]) {
      return c.json({ error: "Feature not available on current plan", feature }, 403);
    }
    await next();
  });
}
