import { TRAINER_TYPES } from "@/features/trainer/trainerRequest";
import type { User } from "@/store/authStore";

/**
 * Who may publish what — the client's matrix, in one place.
 *
 * | Account             | Volunteering | Development (course · workshop · space) | Internship | Events |
 * |---------------------|--------------|------------------------------------------|------------|--------|
 * | Individual          | —            | —                                        | —          | —      |
 * | Individual trainer  | —            | free or paid                             | —          | —      |
 * | Volunteer team      | free         | free only                                | —          | —      |
 * | Organization        | free         | free or paid                             | free only  | yes    |
 *
 * Volunteering and internships are always free; volunteer teams never get the
 * paid option. Every create button, route guard and form reads this rather
 * than checking `user_type` on its own, so the rules cannot drift between
 * screens. The backend enforces the same matrix on save — `PublishPolicy`
 * (BE-93), whose team set matches `case "team"` below exactly — so this is
 * only what the UI *offers*; a wrong offer here is a wasted form, not a
 * widened permission. Unknown organization types wait for their profile.
 */

export type PublisherKind = "individual" | "trainer" | "team" | "organization";
export type PublishIntent = "create" | "edit" | "repost";

/** A repost creates a record; a valid edit target alone can survive a publishing pause. */
export function publishIntentFromNav(value: unknown): PublishIntent {
  if (!value || typeof value !== "object") return "create";
  const { id, isRepublish } = value as { id?: unknown; isRepublish?: unknown };
  if ((typeof id !== "string" && typeof id !== "number") || !Number.isSafeInteger(Number(id)) || Number(id) <= 0) return "create";
  if (isRepublish !== undefined && typeof isRepublish !== "boolean") return "create";
  return isRepublish === true ? "repost" : "edit";
}

export interface PublishPermissions {
  volunteer: boolean;
  /** Course, Class/Workshop and Consultation («مساحة»). */
  development: boolean;
  /** Whether a development opportunity may be paid. Never applies to internships. */
  developmentPaid: boolean;
  internship: boolean;
  events: boolean;
  /**
   * Which development learning types (by `value_en`) may be picked; null means
   * all three. A trainer publishes only what the admin approved them for.
   */
  developmentTypes: string[] | null;
}

export type PublishCapability = keyof Omit<
  PublishPermissions,
  "developmentPaid" | "developmentTypes"
>;

const NONE: PublishPermissions = {
  volunteer: false,
  development: false,
  developmentPaid: false,
  internship: false,
  events: false,
  developmentTypes: null,
};

/**
 * `is_trainer` and `trainer_types` now arrive on every auth payload
 * (BE-95). An individual with neither is not a trainer, so the matrix
 * still denies them everything.
 */
type PublisherUser = Pick<
  User,
  | "user_type"
  | "is_verified"
  | "is_banned"
  | "is_publishing_paused"
  | "organizer_type_display"
  | "is_trainer"
  | "trainer_types"
>;

export function getPublisherKind(
  user: PublisherUser | null | undefined
): PublisherKind | null {
  if (!user) return null;
  if (user.user_type === "organization") {
    if (!user.organizer_type_display?.value_en) return null;
    // BE-186: unknown publisher type grants no capability while the profile loads.
    // OrganizerTypeSync and the protected route resolve it before offering publishing.
    return user.organizer_type_display?.value_en === "Volunteer Team"
      ? "team"
      : "organization";
  }
  return user.is_trainer === true ? "trainer" : "individual";
}

export function getPublishPermissions(
  user: PublisherUser | null | undefined,
  intent: PublishIntent = "create"
): PublishPermissions {
  const kind = getPublisherKind(user);
  const accountPublisher = kind === "organization" || kind === "team";
  /*
   * An individual or trainer who is signed in and banned can only hold an
   * automatic absence ban: since backend `a47169a` a manual ban still holds no
   * session. That ban stops new registration only, not ordinary account use
   * (approved decision 6; PDF p.43), and `PublishPolicy` does not check it, so
   * it does not take a trainer's publishing away. Accounts keep the guard.
   */
  if (!kind || (accountPublisher && user?.is_banned === true) || (accountPublisher && user?.is_publishing_paused === true && intent !== "edit")) return NONE;

  // A team or an organization publishes only once the admin has approved it;
  // `is_verified` is that approval for organization accounts.
  const approved = user?.is_verified === true;

  switch (kind) {
    case "organization":
      return approved
        ? {
            volunteer: true,
            development: true,
            developmentPaid: true,
            internship: true,
            events: true,
            developmentTypes: null,
          }
        : NONE;
    case "team":
      return approved
        ? { ...NONE, volunteer: true, development: true }
        : NONE;
    case "trainer": {
      const approved = TRAINER_TYPES.filter((type) =>
        (user?.trainer_types ?? []).includes(type.slug)
      ).map((type) => type.valueEn);
      return approved.length > 0
        ? { ...NONE, development: true, developmentPaid: true, developmentTypes: approved }
        : NONE;
    }
    default:
      return NONE;
  }
}

/** True when the user may publish at least one of `capabilities`. */
export function canPublish(
  user: PublisherUser | null | undefined,
  capabilities: PublishCapability | PublishCapability[],
  intent: PublishIntent = "create"
): boolean {
  const permissions = getPublishPermissions(user, intent);
  const wanted = Array.isArray(capabilities) ? capabilities : [capabilities];
  return wanted.some((capability) => permissions[capability]);
}
