/**
 * Vercel tool adapters.
 *
 * Credential resolution: vault first (getSecret), falling back to process.env
 * for backwards compatibility during the migration window.
 */

import { getSecret } from '../../secrets.js';
import { wrapFetch } from '../../egress.js';

function resolveCredential(name, options = {}) {
  try {
    const secret = getSecret(name, {
      agent_id: options.agent_id,
      project_id: options.project_id,
    });
    if (secret) return secret;
  } catch {
    // Vault not ready — fall through to process.env.
  }
  return process.env[name] || null;
}

function requireCredential(name, options = {}) {
  const value = resolveCredential(name, options);
  if (!value) throw new Error(`${name} not configured`);
  return value;
}

function vercelHeaders(options = {}) {
  return {
    Authorization: `Bearer ${requireCredential('VERCEL_TOKEN', options)}`,
    Accept: 'application/json',
  };
}

function withTeam(url, teamId) {
  if (teamId) url.searchParams.set('teamId', String(teamId));
  return url;
}

export async function vercelListProjects(input = {}, options = {}) {
  const teamId = input.team_id || resolveCredential('VERCEL_TEAM_ID', options);
  const agentId = options.agent_id ?? null;
  const url = withTeam(new URL('https://api.vercel.com/v9/projects'), teamId);
  if (input.limit) url.searchParams.set('limit', String(Math.min(Math.max(Number(input.limit), 1), 100)));
  const res = await wrapFetch('vercel_list_projects', agentId)(url, { headers: vercelHeaders(options) });
  if (!res.ok) throw new Error(`Vercel projects request failed: ${res.status}`);
  const data = await res.json();
  return {
    projects: (data.projects || []).map(project => ({
      id: project.id,
      name: project.name,
      framework: project.framework,
      latest_deployments: (project.latestDeployments || []).map(dep => ({
        uid: dep.uid,
        url: dep.url,
        state: dep.state,
        created_at: dep.createdAt,
      })),
    })),
  };
}

export async function vercelListDeployments(input = {}, options = {}) {
  const teamId = input.team_id || resolveCredential('VERCEL_TEAM_ID', options);
  const agentId = options.agent_id ?? null;
  const url = withTeam(new URL('https://api.vercel.com/v6/deployments'), teamId);
  if (input.project_id) url.searchParams.set('projectId', String(input.project_id));
  if (input.project_name) url.searchParams.set('projectName', String(input.project_name));
  if (input.limit) url.searchParams.set('limit', String(Math.min(Math.max(Number(input.limit), 1), 100)));
  const res = await wrapFetch('vercel_list_deployments', agentId)(url, { headers: vercelHeaders(options) });
  if (!res.ok) throw new Error(`Vercel deployments request failed: ${res.status}`);
  const data = await res.json();
  return {
    deployments: (data.deployments || []).map(dep => ({
      uid: dep.uid,
      name: dep.name,
      url: dep.url,
      state: dep.state,
      target: dep.target,
      created_at: dep.createdAt,
      creator: dep.creator ? { uid: dep.creator.uid, username: dep.creator.username } : null,
    })),
    pagination: data.pagination || null,
  };
}

export async function vercelCreateDeployment(input = {}) {
  return {
    approval_required: true,
    status: 'pending_approval',
    action: 'vercel_create_deployment',
    summary: input.summary || 'Create a Vercel deployment',
    requested_at: new Date().toISOString(),
    note: 'Deployment creation is staged only. Approve the pending action before any external write is executed.',
  };
}
