import { openStore } from "@/lib/data/store";
import type { UserGroup } from "@/lib/types";

export type Permission =
  | "post" | "comment" | "message" | "sell"
  | "createEvents" | "createCommunities" | "advertise";

/**
 * Whether someone's group allows an action.
 *
 * Permissions were defined and saved but never checked, so every group could
 * do everything. Defaults to allowed when someone has no group, since that's
 * the normal case and a missing group shouldn't lock people out.
 */
export async function may(userId: string, permission: Permission): Promise<boolean> {
  const store = await openStore();
  const user = await store.users.get(userId);
  if (!user) return false;

  // Admins are never restricted by a group.
  if (user.isAdmin) return true;

  const groupId = (user as { groupId?: string }).groupId;
  if (!groupId) return true;

  const groups = await store.small<UserGroup[]>("userGroups", []);
  const group = groups.find((g) => g.id === groupId);
  if (!group) return true;

  return group.can[permission] !== false;
}

/** The message shown when a group forbids something. */
export function refusal(permission: Permission) {
  const wording: Record<Permission, string> = {
    post: "Your account isn't allowed to post",
    comment: "Your account isn't allowed to comment",
    message: "Your account isn't allowed to send messages",
    sell: "Your account isn't allowed to sell",
    createEvents: "Your account isn't allowed to create events",
    createCommunities: "Your account isn't allowed to create groups",
    advertise: "Your account isn't allowed to advertise",
  };
  return wording[permission];
}
