import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { BigCommerceClient } from './clients/bigcommerce.js';
import { registerProductTools } from './tools/products-tools.js';
import { registerOrderTools } from './tools/orders-tools.js';
import { registerCustomerTools } from './tools/customers-tools.js';
import { registerCartTools } from './tools/carts-tools.js';
import { registerCatalogTools } from './tools/catalog-tools.js';
import { registerStoreTools } from './tools/store-tools.js';
import { registerPromotionTools } from './tools/promotions-tools.js';
import { registerWebhookTools } from './tools/webhooks-tools.js';
import { registerContentTools } from './tools/content-tools.js';
import { registerShippingTools } from './tools/shipping-tools.js';

// Initialize BigCommerce client
const storeHash = process.env.BIGCOMMERCE_STORE_HASH;
const accessToken = process.env.BIGCOMMERCE_ACCESS_TOKEN;

if (!storeHash || !accessToken) {
  throw new Error(
    'Missing required environment variables: BIGCOMMERCE_STORE_HASH and BIGCOMMERCE_ACCESS_TOKEN'
  );
}

const client = new BigCommerceClient({
  storeHash,
  accessToken,
  apiVersion: 'v3',
});

// Create MCP server
const server = new Server(
  {
    name: 'bigcommerce-mcp',
    version: '1.0.0',
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// Register all tool sets
const allTools = {
  ...registerProductTools(client),
  ...registerOrderTools(client),
  ...registerCustomerTools(client),
  ...registerCartTools(client),
  ...registerCatalogTools(client),
  ...registerStoreTools(client),
  ...registerPromotionTools(client),
  ...registerWebhookTools(client),
  ...registerContentTools(client),
  ...registerShippingTools(client),
};

// List tools handler
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: Object.entries(allTools).map(([name, tool]) => ({
      name,
      description: tool.description,
      inputSchema: tool.parameters,
    })),
  };
});

// Call tool handler
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const toolName = request.params.name;
  const tool = allTools[toolName as keyof typeof allTools];

  if (!tool) {
    throw new Error(`Unknown tool: ${toolName}`);
  }

  try {
    const result = await tool.handler(request.params.arguments as never);
    return {
      content: [
        {
          type: 'text' as const,
          text: JSON.stringify(result, null, 2),
        },
      ],
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    return {
      content: [
        {
          type: 'text' as const,
          text: JSON.stringify({ error: errorMessage }, null, 2),
        },
      ],
      isError: true,
    };
  }
});

// Start server
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error('BigCommerce MCP Server running on stdio');
}

main().catch((error) => {
  console.error('Fatal error:', error);
  process.exit(1);
});

export { server };
