#!/usr/bin/env node

// Update an existing Linear issue
// Usage: linear-update.js <identifier> [--title <title>] [--state <name>] [--priority <0-4>] [--assignee <name|me>] [--description <text>]

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

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

const identifier = args[0];
if (!identifier || identifier.startsWith("--")) {
	console.log("Usage: linear-update.js <identifier> [options]");
	console.log("\nOptions:");
	console.log("  --title <title>       New title");
	console.log("  --state <name>        New state (e.g. 'In Progress')");
	console.log("  --priority <0-4>      New priority");
	console.log("  --assignee <name|me>  New assignee");
	console.log("  --description <text>  New description");
	process.exit(1);
}

args.shift();

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 title = extractArg("--title");
const stateName = extractArg("--state");
const priority = extractArg("--priority");
const assigneeName = extractArg("--assignee");
const description = extractArg("--description");

const client = getClient();

// Find the issue
const results = await client.searchIssues(identifier, { first: 1 });
const issue = results.nodes[0];
if (!issue) {
	console.error(`Issue '${identifier}' not found.`);
	process.exit(1);
}

const input = {};

if (title) input.title = title;
if (description) input.description = description;
if (priority) input.priority = parseInt(priority, 10);

// Resolve state
if (stateName) {
	const team = await issue.team;
	const states = await team.states();
	const state = states.nodes.find(
		(s) => s.name.toLowerCase() === stateName.toLowerCase()
	);
	if (state) input.stateId = state.id;
	else {
		console.error(`State '${stateName}' not found. Available states:`);
		for (const s of states.nodes) console.error(`  - ${s.name}`);
		process.exit(1);
	}
}

// Resolve assignee
if (assigneeName) {
	if (assigneeName.toLowerCase() === "me") {
		const me = await client.viewer;
		input.assigneeId = me.id;
	} else {
		const users = await client.users({ filter: { name: { containsIgnoreCase: assigneeName } } });
		if (users.nodes[0]) input.assigneeId = users.nodes[0].id;
		else {
			console.error(`User '${assigneeName}' not found.`);
			process.exit(1);
		}
	}
}

if (Object.keys(input).length === 0) {
	console.log("No updates specified. Use --title, --state, --priority, --assignee, or --description.");
	process.exit(1);
}

await client.updateIssue(issue.id, input);
console.log(`Updated ${issue.identifier}: ${issue.title}`);
console.log(`URL: ${issue.url}`);
