import axios from 'axios';

declare global {
  interface Window {
    __APP_CONFIG__?: { apiUrl?: string; authUrl?: string; };
  }
}

const BASE     = window.__APP_CONFIG__?.apiUrl  || 'http://localhost:8099';
const AUTH_BASE = window.__APP_CONFIG__?.authUrl || 'http://localhost:8082';

const TOKEN_KEY = 'guide_token';

export function getToken(): string | null { return localStorage.getItem(TOKEN_KEY); }
export function setToken(t: string)       { localStorage.setItem(TOKEN_KEY, t); }
export function clearToken()              { localStorage.removeItem(TOKEN_KEY); }

const api = axios.create({
  baseURL: BASE,
  headers: { 'Content-Type': 'application/json' },
});
api.interceptors.request.use(cfg => {
  const t = getToken();
  if (t) cfg.headers['Authorization'] = `Bearer ${t}`;
  return cfg;
});

export const authApi = axios.create({
  baseURL: AUTH_BASE,
  headers: { 'Content-Type': 'application/json' },
});

export default api;

// ── Guide content API ──────────────────────────────────────
export interface NavTab    { tab: string; order: number; audience: string; }
export interface NavModule { module: string; title: string; tabs: NavTab[]; }
export interface NavApp    { app: string; modules: NavModule[]; }
export interface ModuleTab { tab: string; order: number; audience: string; body: string; }
export interface ModuleView { module: string; title: string; tabs: ModuleTab[]; }

/** apps → modules → tabs (audience-filtered server-side by the caller's role). */
export async function fetchNav(): Promise<NavApp[]> {
  const res = await api.get('/api/v1/guide/nav');
  return res.data;
}

/** one module with its tabs (markdown bodies). */
export async function fetchModule(module: string): Promise<ModuleView> {
  const res = await api.get(`/api/v1/guide/modules/${encodeURIComponent(module)}`);
  return res.data;
}

/** submit in-guide feedback → creates a Gitea Bug/Enhancement issue. */
export async function submitFeedback(payload: {
  type: string; area: string; title: string; description: string; module?: string;
}): Promise<{ number: number; url: string }> {
  const res = await api.post('/api/v1/guide/feedback', payload);
  return res.data;
}
