import { config } from '../config.js';

export type ToolSecurityScheme =
  | { type: 'noauth' }
  | { type: 'oauth2'; scopes?: string[] };

const toolSecuritySchemes = new Map<string, ToolSecurityScheme[]>();

export const setToolSecuritySchemes = (name: string, schemes: ToolSecurityScheme[]) => {
  toolSecuritySchemes.set(name, schemes);
};

export const getToolSecuritySchemes = () => toolSecuritySchemes;

export const noAuthSchemes = (): ToolSecurityScheme[] => [{ type: 'noauth' }];

export const oauth2Schemes = (): ToolSecurityScheme[] => {
  const scopes = config.proovit.authScopes;
  return scopes && scopes.length ? [{ type: 'oauth2', scopes }] : [{ type: 'oauth2' }];
};

export const handleApiError = (error: any) => {
  if (error.response?.status === 401 || error.message === "AUTHENTICATION_REQUIRED") {
    return {
      isError: true,
      content: [{ type: "text" as const, text: "Authentication required." }],
      _meta: {
        "mcp/www_authenticate": {
          uri: "proovit://auth",
          error: "insufficient_scope",
          error_description: "Please log in to access this feature."
        }
      }
    };
  }
  return { isError: true, content: [{ type: "text" as const, text: `Error: ${error.message}` }] };
};
