const fs = require('fs');
const path = require('path');

const { getDataDir } = require('./runtime');

const DEFAULT_CLOUD_API_URL = 'https://api.orgboard.iacovici.it/v1';
const DEFAULT_SUPABASE_URL = 'https://qgaeonmhvxrkylyhjqvf.supabase.co';
const DEFAULT_SUPABASE_PUBLISHABLE_KEY = 'sb_publishable_uWO8unZaik89204UsyNwsw_spEFUDfO';
const DEFAULT_PUBLIC_APP_URL = 'https://orgboard.iacovici.it';

function readCloudConfigFile() {
  const filePath = path.join(getDataDir(), 'cloud-config.json');
  if (!fs.existsSync(filePath)) return {};
  try {
    return JSON.parse(fs.readFileSync(filePath, 'utf8')) || {};
  } catch {
    return {};
  }
}

function writeCloudConfigFile(payload = {}) {
  const filePath = path.join(getDataDir(), 'cloud-config.json');
  const nextPayload = {
    cloudApiUrl: payload.cloudApiUrl || DEFAULT_CLOUD_API_URL,
    supabaseUrl: payload.supabaseUrl || DEFAULT_SUPABASE_URL,
    supabasePublishableKey: payload.supabasePublishableKey || DEFAULT_SUPABASE_PUBLISHABLE_KEY,
    publicAppUrl: payload.publicAppUrl || DEFAULT_PUBLIC_APP_URL
  };
  fs.writeFileSync(filePath, JSON.stringify(nextPayload, null, 2));
  return nextPayload;
}

function getCloudClientConfig() {
  const fileConfig = readCloudConfigFile();
  const cloudApiUrl = process.env.ORG_BOARD_CLOUD_API_URL || fileConfig.cloudApiUrl || DEFAULT_CLOUD_API_URL;
  const supabaseUrl = process.env.ORG_BOARD_SUPABASE_URL || fileConfig.supabaseUrl || DEFAULT_SUPABASE_URL;
  const supabasePublishableKey =
    process.env.ORG_BOARD_SUPABASE_PUBLISHABLE_KEY
    || process.env.SUPABASE_PUBLISHABLE_KEY
    || fileConfig.supabasePublishableKey
    || DEFAULT_SUPABASE_PUBLISHABLE_KEY;
  const publicAppUrl =
    process.env.ORG_BOARD_PUBLIC_APP_URL
    || fileConfig.publicAppUrl
    || DEFAULT_PUBLIC_APP_URL;

  return {
    cloudApiUrl,
    supabaseUrl,
    supabasePublishableKey,
    publicAppUrl,
    authReady: Boolean(cloudApiUrl && supabaseUrl && supabasePublishableKey)
  };
}

module.exports = {
  getCloudClientConfig,
  writeCloudConfigFile
};
