'use strict';

const fs = require('fs');
const path = require('path');
const slackMcp = require('./slack-mcp');

const OWNER_ENV_KEY = 'SLACK_OWNER_USER_ID';

function getEnvPath() {
  return process.env.WALLE_ENV_PATH || path.resolve(__dirname, '..', '..', '.env');
}

function normalizeSlackUserId(value) {
  const id = String(value || '').trim();
  if (!id || /[\r\n=]/.test(id)) return '';
  return /^[A-Z][A-Z0-9]{2,}$/.test(id) ? id : '';
}

function readOwnerUserIdFromToken() {
  const token = slackMcp.loadToken();
  return normalizeSlackUserId(token?.user_id || token?.authed_user?.id || token?.user?.id || '');
}

function persistEnvVar(key, value, envPath = getEnvPath()) {
  const safeKey = String(key || '').replace(/[^A-Z0-9_]/g, '');
  const safeValue = String(value || '').trim();
  if (!safeKey || !safeValue || /[\r\n]/.test(safeValue)) {
    throw new Error('Invalid environment value');
  }

  const lines = [];
  try {
    for (const line of fs.readFileSync(envPath, 'utf8').split('\n')) {
      const m = line.match(/^\s*#?\s*([A-Z0-9_]+)\s*=/);
      if (m && m[1] === safeKey) continue;
      lines.push(line);
    }
  } catch {
    lines.push('# Wall-E configuration');
    lines.push('');
  }
  while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop();
  lines.push('');
  lines.push(`${safeKey}=${safeValue}`);

  const dir = path.dirname(envPath);
  fs.mkdirSync(dir, { recursive: true });
  const tmpPath = `${envPath}.${process.pid}.${Date.now()}.tmp`;
  fs.writeFileSync(tmpPath, lines.join('\n') + '\n', { mode: 0o600 });
  fs.renameSync(tmpPath, envPath);
}

function repairSlackOwnerIdentity(opts = {}) {
  const existing = normalizeSlackUserId(process.env[OWNER_ENV_KEY]);
  if (existing) {
    return { ok: true, alreadyConfigured: true, userId: existing, source: 'env', persisted: false };
  }

  const tokenUserId = readOwnerUserIdFromToken();
  if (!tokenUserId) {
    return {
      ok: false,
      error: 'Connect Slack first so Wall-E can identify your Slack account automatically.',
      needsSlackAuth: true,
    };
  }

  let persisted = false;
  if (opts.persist !== false) {
    persistEnvVar(OWNER_ENV_KEY, tokenUserId, opts.envPath);
    persisted = true;
  }
  process.env[OWNER_ENV_KEY] = tokenUserId;

  return {
    ok: true,
    alreadyConfigured: false,
    userId: tokenUserId,
    source: 'slack_oauth_token',
    persisted,
  };
}

function getSlackOwnerRepairState() {
  const envUserId = normalizeSlackUserId(process.env[OWNER_ENV_KEY]);
  if (envUserId) return { configured: true, canRepair: false, userId: envUserId, source: 'env' };
  const tokenUserId = readOwnerUserIdFromToken();
  return {
    configured: false,
    canRepair: !!tokenUserId,
    userId: tokenUserId || '',
    source: tokenUserId ? 'slack_oauth_token' : null,
  };
}

module.exports = {
  OWNER_ENV_KEY,
  getEnvPath,
  getSlackOwnerRepairState,
  normalizeSlackUserId,
  persistEnvVar,
  readOwnerUserIdFromToken,
  repairSlackOwnerIdentity,
};
