#!/usr/bin/env node

// List Linear projects
// Usage: linear-projects.js [--team <key>] [-n <num>]

import { getClient, formatDate } from "./lib.js";

const args = process.argv.slice(2);

function extractArg(flag) {
	const idx = args.indexOf(flag);
	if (idx !== -1 && args[idx + 1]) {
		const val = args[idx + 1];
		args.splice(idx, 2);
		return val;
	}
	return null;
}

const numResults = parseInt(extractArg("-n") || "25", 10);
const teamKey = extractArg("--team");

const client = getClient();

const filter = {};
if (teamKey) {
	filter.accessibleTeams = { key: { eq: teamKey.toUpperCase() } };
}

const projects = await client.projects({ filter, first: numResults });

if (projects.nodes.length === 0) {
	console.log("No projects found.");
	process.exit(0);
}

for (const project of projects.nodes) {
	const lead = await project.lead;
	console.log(`--- ${project.name} ---`);
	console.log(`State: ${project.state} | Progress: ${Math.round(project.progress * 100)}%`);
	if (lead) console.log(`Lead: ${lead.name}`);
	if (project.targetDate) console.log(`Target: ${project.targetDate}`);
	console.log(`URL: ${project.url}`);
	console.log("");
}
