/* Nutri Movie Night — OMDb client (window.OMDB).
   Used ONLY for the real IMDb rating (imdbRating + imdbVotes). NOT for posters,
   metadata, overview, genres or recommendations — those stay on TMDb. Free tier only.

   The OMDb API key is NEVER hardcoded — the user pastes it in Movie Night → Settings
   and it is stored (user-specific) alongside the TMDb creds in Store.movieCredentials():
     { apiKey, readToken, omdbApiKey }
   Placeholder only, for reference:
     OMDB_API_KEY=your_omdb_api_key_here

   Request shape (by IMDb id):
     https://www.omdbapi.com/?i=IMDB_ID&apikey=OMDB_API_KEY
   We use https (the PWA is served over https — http would be mixed-content blocked)
   and cache:'no-store' so the key is never persisted by the SW. */
(function () {
  const BASE = 'https://www.omdbapi.com/';

  function _key() {
    try {
      const c = (window.Store && window.Store.movieCredentials && window.Store.movieCredentials()) || {};
      return (c.omdbApiKey || '').trim();
    } catch (_) { return ''; }
  }
  // The IMDb rating now comes through the secure backend proxy (movieApi). The local
  // OMDb key is only a pre-deploy fallback. "Has key" = proxy reachable OR local key.
  function _proxyFn() {
    try {
      if (window.TMDB && window.TMDB.proxyAvailable && !window.TMDB.proxyAvailable()) return null;
      if (window.firebase && firebase.app && firebase.functions) return firebase.app().functions().httpsCallable('movieApi');
    } catch (_) {}
    return null;
  }
  function hasKey() {
    if (window.TMDB && window.TMDB.proxyAvailable && window.TMDB.proxyAvailable()) return true;
    return !!_key();
  }

  // Parse OMDb's stringy fields into clean numbers (or null when "N/A").
  function _parseRating(s) {
    if (!s || s === 'N/A') return null;
    const n = parseFloat(s);
    return isNaN(n) ? null : +n.toFixed(1);
  }
  function _parseVotes(s) {
    if (!s || s === 'N/A') return null;
    const n = parseInt(String(s).replace(/[,\s]/g, ''), 10);
    return isNaN(n) ? null : n;
  }

  async function _get(params) {
    // Backend proxy first (key lives on the server).
    const fn = _proxyFn();
    if (fn) {
      try { const res = await fn({ service: 'omdb', params: params || {} }); return res.data; }
      catch (e) {
        const permanent = e && /functions\/(not-found|unimplemented|failed-precondition|internal|unavailable)/.test(e.code || '');
        if (!_key()) { const er = new Error(permanent ? 'OMDb not connected. Deploy the Movie Night functions (DEPLOY_FUNCTIONS.md).' : ((e && e.message) || 'OMDb service error.')); er.code = permanent ? 'no-key' : ((e && e.code) || 'http'); throw er; }
        // else fall through to legacy direct key
      }
    }
    const key = _key();
    if (!key) { const e = new Error('OMDb not connected. Deploy the Movie Night functions (or add an OMDb key in Settings → Developer).'); e.code = 'no-key'; throw e; }
    const url = new URL(BASE);
    url.searchParams.set('apikey', key);
    Object.keys(params || {}).forEach(k => {
      if (params[k] !== undefined && params[k] !== null && params[k] !== '') url.searchParams.set(k, params[k]);
    });
    let res;
    try {
      res = await fetch(url.toString(), { method: 'GET', cache: 'no-store' });
    } catch (netErr) {
      const e = new Error('Network error reaching OMDb. Check your connection and try again.'); e.code = 'network'; throw e;
    }
    if (res.status === 401) { const e = new Error('OMDb rejected your key (401).'); e.code = 'auth'; throw e; }
    if (!res.ok) { const e = new Error('OMDb error (HTTP ' + res.status + ').'); e.code = 'http'; throw e; }
    const data = await res.json();
    if (data && data.Response === 'False') {
      const e = new Error(data.Error || 'OMDb returned no result.');
      e.code = /invalid api key/i.test(data.Error || '') ? 'auth'
        : /request limit/i.test(data.Error || '') ? 'rate-limit'
        : 'not-found';
      throw e;
    }
    return data;
  }

  // Fetch the real IMDb rating for one movie by its IMDb id.
  // Returns { imdbId, imdbRating, imdbVotes, title, year } — rating/votes may be null.
  async function byImdb(imdbId) {
    if (!imdbId) { const e = new Error('Missing IMDb id.'); e.code = 'no-id'; throw e; }
    const d = await _get({ i: imdbId, tomatoes: 'false' });
    return {
      imdbId: d.imdbID || imdbId,
      imdbRating: _parseRating(d.imdbRating),
      imdbVotes: _parseVotes(d.imdbVotes),
      title: d.Title || '',
      year: d.Year ? parseInt(d.Year, 10) || null : null,
    };
  }

  // Cheap auth check — uses a well-known IMDb id so a valid key always resolves.
  async function testConnection() {
    try {
      const d = await byImdb('tt0111161'); // The Shawshank Redemption
      return { ok: true, message: 'Connected to OMDb ✓' + (d.imdbRating != null ? ' (IMDb ' + d.imdbRating + ')' : '') };
    } catch (e) {
      return { ok: false, code: e.code || 'error', message: e.message || 'Connection failed.' };
    }
  }

  window.OMDB = {
    hasKey, byImdb, testConnection, BASE,
    ATTRIBUTION: 'IMDb ratings via the OMDb API (omdbapi.com).',
  };
})();
