// osv vulnerability — fetch a single OSV vulnerability by id.
//
// Hits `https://api.osv.dev/v1/vulns/<id>`. Returns one row with the canonical
// id, summary, severity, aliases (CVE / GHSA mappings), publish / modify dates,
// and the affected packages (flattened to a comma-separated "ecosystem:name" list).
import { cli, Strategy } from '@jackwener/opencli/registry';
import { EmptyResultError } from '@jackwener/opencli/errors';
import { OSV_BASE, osvGet, requireVulnId, severityLabel, trimDate } from './utils.js';

cli({
    site: 'osv',
    name: 'vulnerability',
    access: 'read',
    description: 'Single OSV.dev vulnerability detail (severity, affected packages, CVE/GHSA aliases)',
    domain: 'osv.dev',
    strategy: Strategy.PUBLIC,
    browser: false,
    args: [
        { name: 'id', positional: true, type: 'string', required: true, help: 'OSV vulnerability id (e.g. "GHSA-29mw-wpgm-hmr9", "CVE-2020-28500")' },
    ],
    columns: [
        'id', 'summary', 'severity', 'aliases', 'published', 'modified',
        'affectedPackages', 'cwes', 'referenceCount', 'url',
    ],
    func: async (args) => {
        const id = requireVulnId(args.id);
        const vuln = await osvGet(`${OSV_BASE}/v1/vulns/${encodeURIComponent(id)}`, `osv vulnerability ${id}`);
        if (!vuln || !vuln.id) {
            throw new EmptyResultError('osv vulnerability', `OSV.dev returned no record for "${id}".`);
        }
        const affected = Array.isArray(vuln.affected) ? vuln.affected : [];
        const pkgPairs = [];
        for (const a of affected) {
            const eco = a?.package?.ecosystem;
            const name = a?.package?.name;
            if (eco && name) pkgPairs.push(`${eco}:${name}`);
        }
        const aliases = Array.isArray(vuln.aliases) ? vuln.aliases.filter(Boolean) : [];
        const cwes = Array.isArray(vuln?.database_specific?.cwe_ids) ? vuln.database_specific.cwe_ids : [];
        const refs = Array.isArray(vuln.references) ? vuln.references : [];
        return [{
            id: String(vuln.id),
            summary: String(vuln.summary ?? '').trim(),
            severity: severityLabel(vuln),
            aliases: aliases.join(', '),
            published: trimDate(vuln.published),
            modified: trimDate(vuln.modified),
            affectedPackages: pkgPairs.join(', '),
            cwes: cwes.join(', '),
            referenceCount: refs.length,
            url: `https://osv.dev/vulnerability/${vuln.id}`,
        }];
    },
});
