/**
 * Salesforce MCP Server Entry Point
 */

import { SalesforceServer } from './server.js';
import { z } from 'zod';

// Environment variable schema
const EnvSchema = z.object({
  SF_ACCESS_TOKEN: z.string().min(1, 'SF_ACCESS_TOKEN is required'),
  SF_INSTANCE_URL: z.string().url('SF_INSTANCE_URL must be a valid URL'),
  SF_API_VERSION: z.string().optional().default('v59.0'),
});

/**
 * Validate environment variables
 */
function validateEnv() {
  try {
    return EnvSchema.parse({
      SF_ACCESS_TOKEN: process.env.SF_ACCESS_TOKEN,
      SF_INSTANCE_URL: process.env.SF_INSTANCE_URL,
      SF_API_VERSION: process.env.SF_API_VERSION,
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      console.error('Environment validation failed:');
      error.errors.forEach((err) => {
        console.error(`  - ${err.path.join('.')}: ${err.message}`);
      });
      process.exit(1);
    }
    throw error;
  }
}

/**
 * Health check endpoint (if needed for HTTP transport)
 */
function healthCheck(): { status: string; timestamp: string } {
  return {
    status: 'ok',
    timestamp: new Date().toISOString(),
  };
}

/**
 * Main function
 */
async function main() {
  // Validate environment
  const env = validateEnv();

  console.error('Starting Salesforce MCP Server...');
  console.error(`Instance URL: ${env.SF_INSTANCE_URL}`);
  console.error(`API Version: ${env.SF_API_VERSION}`);

  // Create and start server
  const server = new SalesforceServer({
    accessToken: env.SF_ACCESS_TOKEN,
    instanceUrl: env.SF_INSTANCE_URL,
    apiVersion: env.SF_API_VERSION,
  });

  // Graceful shutdown handlers
  const shutdown = async (signal: string) => {
    console.error(`\nReceived ${signal}, shutting down gracefully...`);
    try {
      await server.close();
      console.error('Server closed successfully');
      process.exit(0);
    } catch (error) {
      console.error('Error during shutdown:', error);
      process.exit(1);
    }
  };

  process.on('SIGINT', () => shutdown('SIGINT'));
  process.on('SIGTERM', () => shutdown('SIGTERM'));

  // Handle uncaught errors
  process.on('uncaughtException', (error) => {
    console.error('Uncaught exception:', error);
    shutdown('uncaughtException');
  });

  process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled rejection at:', promise, 'reason:', reason);
    shutdown('unhandledRejection');
  });

  // Start server (stdio transport by default)
  try {
    await server.start();
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

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