import axios from 'axios';
import https from 'https';

const agent = new https.Agent({ rejectUnauthorized: false });

let baseURL = '';
let cookies = '';
let csrfToken = '';

function getEnvConfig() {
  const ip = process.env.UDR_IP;
  const user = process.env.UDR_USER;
  const pass = process.env.UDR_PASSWORD;
  if (!ip || !user || !pass) {
    return null;
  }
  return { ip, user, pass };
}

const client = axios.create({ httpsAgent: agent, timeout: 10000 });

client.interceptors.response.use(
  (res) => res,
  async (error) => {
    const original = error.config;
    if (error.response?.status === 401 && !original._retry) {
      original._retry = true;
      await login();
      original.headers['Cookie'] = cookies;
      original.headers['x-csrf-token'] = csrfToken;
      return client(original);
    }
    return Promise.reject(error);
  }
);

export async function login() {
  const config = getEnvConfig();
  if (!config) {
    console.warn('[UniFi] No UDR credentials configured - running in demo mode');
    return false;
  }
  baseURL = `https://${config.ip}`;
  try {
    const res = await axios.post(
      `${baseURL}/api/auth/login`,
      { username: config.user, password: config.pass },
      { httpsAgent: agent, timeout: 10000 }
    );
    const setCookie = res.headers['set-cookie'];
    if (setCookie) {
      cookies = setCookie.map((c) => c.split(';')[0]).join('; ');
    }
    csrfToken = res.headers['x-csrf-token'] || '';
    console.log('[UniFi] Authenticated successfully');
    return true;
  } catch (err) {
    console.error('[UniFi] Login failed:', err.message);
    return false;
  }
}

function authHeaders() {
  return {
    Cookie: cookies,
    'x-csrf-token': csrfToken,
  };
}

export async function getTrafficRules() {
  if (!baseURL) return [];
  const res = await client.get(
    `${baseURL}/proxy/network/v2/api/site/default/trafficrules`,
    { headers: authHeaders() }
  );
  return res.data;
}

export async function getTrafficRule(ruleId) {
  if (!baseURL) return null;
  const rules = await getTrafficRules();
  const list = Array.isArray(rules) ? rules : rules?.data || [];
  return list.find((r) => r._id === ruleId) || null;
}

export async function updateTrafficRule(ruleId, rulePayload) {
  if (!baseURL) return null;
  const res = await client.put(
    `${baseURL}/proxy/network/v2/api/site/default/trafficrules/${ruleId}`,
    rulePayload,
    { headers: { ...authHeaders(), 'Content-Type': 'application/json' } }
  );
  return res.data;
}

export async function getClients() {
  if (!baseURL) return [];
  const res = await client.get(
    `${baseURL}/proxy/network/api/s/default/stat/sta`,
    { headers: authHeaders() }
  );
  return res.data?.data || res.data || [];
}

export async function blockClient(mac) {
  if (!baseURL) return null;
  const res = await client.post(
    `${baseURL}/proxy/network/api/s/default/cmd/stamgr`,
    { cmd: 'block-sta', mac: mac.toLowerCase() },
    { headers: { ...authHeaders(), 'Content-Type': 'application/json' } }
  );
  return res.data;
}

export async function unblockClient(mac) {
  if (!baseURL) return null;
  const res = await client.post(
    `${baseURL}/proxy/network/api/s/default/cmd/stamgr`,
    { cmd: 'unblock-sta', mac: mac.toLowerCase() },
    { headers: { ...authHeaders(), 'Content-Type': 'application/json' } }
  );
  return res.data;
}
