#!/usr/bin/env node

// Search Linear issues by text query
// Usage: linear-search.js <query> [-n <num>] [--team <key>] [--state <name>]

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

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

let numResults = 10;
const nIdx = args.indexOf("-n");
if (nIdx !== -1 && args[nIdx + 1]) {
	numResults = parseInt(args[nIdx + 1], 10);
	args.splice(nIdx, 2);
}

let teamFilter = null;
const teamIdx = args.indexOf("--team");
if (teamIdx !== -1 && args[teamIdx + 1]) {
	teamFilter = args[teamIdx + 1];
	args.splice(teamIdx, 2);
}

let stateFilter = null;
const stateIdx = args.indexOf("--state");
if (stateIdx !== -1 && args[stateIdx + 1]) {
	stateFilter = args[stateIdx + 1];
	args.splice(stateIdx, 2);
}

const query = args.join(" ");

if (!query) {
	console.log("Usage: linear-search.js <query> [-n <num>] [--team <key>] [--state <name>]");
	console.log("\nOptions:");
	console.log("  -n <num>         Number of results (default: 10)");
	console.log("  --team <key>     Filter by team key (e.g. ENG)");
	console.log("  --state <name>   Filter by state name (e.g. 'In Progress')");
	process.exit(1);
}

const client = getClient();

const results = await client.searchIssues(query, { first: numResults });

for (const issue of results.nodes) {
	const state = await issue.state;
	const team = await issue.team;
	const assignee = await issue.assignee;

	if (teamFilter && team?.key?.toLowerCase() !== teamFilter.toLowerCase()) continue;
	if (stateFilter && state?.name?.toLowerCase() !== stateFilter.toLowerCase()) continue;

	console.log(`--- ${issue.identifier} ---`);
	console.log(`Title: ${issue.title}`);
	console.log(`State: ${state?.name || "Unknown"}`);
	console.log(`Priority: ${issue.priorityLabel}`);
	console.log(`Team: ${team?.key || "?"} | Assignee: ${assignee?.name || "Unassigned"}`);
	console.log(`Created: ${formatDate(issue.createdAt)} | Updated: ${formatDate(issue.updatedAt)}`);
	if (issue.description) console.log(`Description: ${truncate(issue.description, 200)}`);
	console.log(`URL: ${issue.url}`);
	console.log("");
}

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