const DEFAULT_BASE_URL = 'http://localhost:3000';

function normalizeBaseUrl(rawBaseUrl) {
  if (typeof rawBaseUrl !== 'string' || rawBaseUrl.trim().length === 0) {
    return DEFAULT_BASE_URL;
  }

  return rawBaseUrl.trim().replace(/\/+$/, '');
}

async function getRecipeManagerBaseUrl() {
  const { recipeManagerBaseUrl } = await chrome.storage.sync.get({
    recipeManagerBaseUrl: DEFAULT_BASE_URL,
  });

  return normalizeBaseUrl(recipeManagerBaseUrl);
}

async function sendUrlToRecipeManager(pageUrl) {
  const baseUrl = await getRecipeManagerBaseUrl();
  const importUrl = `${baseUrl}/api/import/url`;

  const response = await fetch(importUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ url: pageUrl }),
  });

  if (!response.ok) {
    const responseText = await response.text();
    throw new Error(`Import request failed (${response.status}): ${responseText}`);
  }

  return response.json();
}

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'send-to-recipe-manager',
    title: 'Send to Recipe Manager',
    contexts: ['page'],
  });
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId !== 'send-to-recipe-manager' || !tab?.url) {
    return;
  }

  sendUrlToRecipeManager(tab.url)
    .then((payload) => {
      console.info('[Recipe Manager Extension] Import request sent successfully', {
        sourceUrl: tab.url,
        success: payload?.success ?? true,
      });
    })
    .catch((error) => {
      console.error('[Recipe Manager Extension] Failed to import URL', {
        sourceUrl: tab.url,
        error: error instanceof Error ? error.message : String(error),
      });
    });
});
