import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';

const logger = getLogger('sync-routes');

export function createSyncRoutes(container: IServiceContainer) {
  const sync = new Hono();

  // Manual sync trigger endpoints
  sync.post('/symbols', async c => {
    try {
      const queueManager = container.queue;
      if (!queueManager) {
        return c.json({ success: false, error: 'Queue manager not available' }, 503);
      }

      const symbolsQueue = queueManager.getQueue('symbols');

      const job = await symbolsQueue.addJob('sync-qm-symbols', {
        handler: 'symbols',
        operation: 'sync-qm-symbols',
        payload: {},
      });

      return c.json({ success: true, jobId: job.id, message: 'QM symbols sync job queued' });
    } catch (error) {
      logger.error('Failed to queue symbol sync job', { error });
      return c.json(
        { success: false, error: error instanceof Error ? error.message : 'Unknown error' },
        500
      );
    }
  });

  sync.post('/exchanges', async c => {
    try {
      const queueManager = container.queue;
      if (!queueManager) {
        return c.json({ success: false, error: 'Queue manager not available' }, 503);
      }

      const exchangesQueue = queueManager.getQueue('exchanges');

      const job = await exchangesQueue.addJob('sync-qm-exchanges', {
        handler: 'exchanges',
        operation: 'sync-qm-exchanges',
        payload: {},
      });

      return c.json({ success: true, jobId: job.id, message: 'QM exchanges sync job queued' });
    } catch (error) {
      logger.error('Failed to queue exchange sync job', { error });
      return c.json(
        { success: false, error: error instanceof Error ? error.message : 'Unknown error' },
        500
      );
    }
  });

  sync.post('/symbols/:provider', async c => {
    try {
      const provider = c.req.param('provider');
      const queueManager = container.queue;
      if (!queueManager) {
        return c.json({ success: false, error: 'Queue manager not available' }, 503);
      }

      const symbolsQueue = queueManager.getQueue('symbols');

      const job = await symbolsQueue.addJob('sync-symbols-from-provider', {
        handler: 'symbols',
        operation: 'sync-symbols-from-provider',
        payload: { provider },
      });

      return c.json({
        success: true,
        jobId: job.id,
        message: `${provider} symbols sync job queued`,
      });
    } catch (error) {
      logger.error('Failed to queue provider symbol sync job', { error });
      return c.json(
        { success: false, error: error instanceof Error ? error.message : 'Unknown error' },
        500
      );
    }
  });

  return sync;
}
