import type { ShowToast } from './type-helpers/toast';
import type { OpenDialog } from './type-helpers/dialog';
import type { OpenAssetPicker } from './type-helpers/openAssetPicker';

// see https://github.com/krakenjs/zoid/blob/master/src/component/props.js#L53
export const reservedExtensionProps = [
  'timeout',
  'window',
  'close',
  'focus',
  'resize',
  'uid',
  'cspNonce',
  'getParent',
  'getParentDomain',
  'hide',
  'show',
  'export',
  'onDisplay',
  'onRendered',
  'onRender',
  'onClose',
  'onDestroy',
  'onResize',
  'onFocus',
  'onError',
  'onProps',
];

export enum ExtensionPermission {
  INPUT = 'INPUT',
  FORM = 'FORM',
  API = 'API',
}

type ConfigVariableName = string;

type ConfigVariableSettings = {
  type: 'string' | 'number' | 'boolean';
  displayName?: string;
  description?: string;
  required?: boolean;
  defaultValue?: any;
};

export type ConfigFields = Record<ConfigVariableName, ConfigVariableSettings>;

export type ConfigValue = Record<
  string,
  boolean | number | string | undefined | null
>;

export type FieldConfig = {
  tableConfig: ConfigValue;
  fieldConfig: ConfigValue;
};

export type FormSidebarConfig = { sidebarConfig: ConfigValue };

export type Project = {
  id: string;
  name: string;
  mgmtApi: string;
  mgmtToken: string;
};

export type Environment = {
  id: string;
  name: string;
  endpoint: string;
  authToken: string;
};

export type User = {
  id: string;
};

export type Context = {
  /**
   * The project that the app is running in
   */
  project: Project;
  /**
   * The environment that the app is running in
   */
  environment: Environment;
  /**
   * The user that is currently logged in
   * Available only to apps that have read User permission
   *
   * Intended to be used to fetch user's permissions and roles
   * from the management API using the user's ID.
   *
   * @example
   * ```graphql
   * query user_query($id: ID!) {
   *   viewer {
   *     ... on AppTokenViewer {
   *       id
   *       user(id: $id) {
   *         permissions
   *         roles {
   *           name
   *           isDefault
   *         }
   *       }
   *     }
   *   }
   * }
   * ```
   */
  user?: User;
};

export interface ExtensionPropsBase {
  context: Context;
  openDialog: OpenDialog;
  showToast: ShowToast;
  openAssetPicker: OpenAssetPicker;
  redirectParent: (location: string | Location) => Promise<void>;
  historyReplace: (url: string | HistoryCallback) => Promise<void>;
  historyPush: (url: string | HistoryCallback) => Promise<void>;
}

export interface ExtensionDialogProps extends ExtensionPropsBase {
  onCloseDialog: (value: any) => void;
}

type HistoryCallback = (href: Location['href']) => string;
