import { OrderCollector } from './OrderCollector';
import { ReturnSync } from './ReturnSync';
import { RefundQuery } from './RefundQuery';
import { MessageHandler } from './MessageHandler';
import { Logger } from '../utils/Logger';

const logger = new Logger('Background');

const orderCollector = new OrderCollector();
const returnSync = new ReturnSync();
const refundQuery = new RefundQuery();
const messageHandler = new MessageHandler(orderCollector, returnSync, refundQuery);

chrome.runtime.onInstalled.addListener((details) => {
  logger.info('Extension installed', { reason: details.reason });
  
  if (details.reason === 'install') {
    chrome.storage.local.set({
      initialized: true,
      config: {
        apiEndpoint: 'http://localhost:3003',
        syncInterval: 300000,
        maxRetries: 3,
      },
    });
  }
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  logger.info('Message received', { type: message.type, sender: sender.tab?.id });
  
  messageHandler.handle(message, sender)
    .then((result) => sendResponse({ success: true, data: result }))
    .catch((error) => {
      logger.error('Message handler error', { error: error.message });
      sendResponse({ success: false, error: error.message });
    });
  
  return true;
});

chrome.alarms.onAlarm.addListener(async (alarm) => {
  logger.info('Alarm triggered', { name: alarm.name });
  
  switch (alarm.name) {
    case 'orderSync':
      await orderCollector.syncAllShops();
      break;
    case 'returnSync':
      await returnSync.syncAllReturns();
      break;
    case 'refundQuery':
      await refundQuery.queryAllRefunds();
      break;
  }
});

async function setupAlarms() {
  const config = await chrome.storage.local.get('config');
  const syncInterval = config.config?.syncInterval || 300000;
  
  chrome.alarms.create('orderSync', { periodInMinutes: syncInterval / 60000 });
  chrome.alarms.create('returnSync', { periodInMinutes: (syncInterval * 2) / 60000 });
  chrome.alarms.create('refundQuery', { periodInMinutes: (syncInterval * 3) / 60000 });
  
  logger.info('Alarms setup complete', { syncInterval });
}

setupAlarms();

export { orderCollector, returnSync, refundQuery };
