#!/usr/bin/env node

// Update task status via API (requires existing session cookie)
// Usage: node scripts/update-task-status.js <task-id> <status>

const API_URL = process.env.API_URL || 'http://localhost:3000/api';
const COOKIE_FILE = process.env.GANTT_COOKIE_FILE || `${process.env.HOME || ''}/.config/gantt-board/cookies.txt`;

const taskId = process.argv[2];
const status = process.argv[3] || 'review';

if (!taskId) {
  console.error('Usage: node scripts/update-task-status.js <task-id> <status>');
  process.exit(1);
}

async function readCookieHeader(filePath) {
  const fs = await import('node:fs');
  if (!fs.existsSync(filePath)) return '';
  const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/).filter(Boolean);
  const cookies = [];
  for (const line of lines) {
    if (line.startsWith('#')) continue;
    const parts = line.split('\t');
    if (parts.length >= 7) {
      cookies.push(`${parts[5]}=${parts[6]}`);
    }
  }
  return cookies.join('; ');
}

async function main() {
  const cookieHeader = await readCookieHeader(COOKIE_FILE);
  if (!cookieHeader) {
    console.error(`No session cookie found at ${COOKIE_FILE}. Login first: ./scripts/gantt.sh auth login <email> <password>`);
    process.exit(1);
  }

  const getRes = await fetch(`${API_URL}/tasks?taskId=${encodeURIComponent(taskId)}&include=detail`, {
    headers: {
      Cookie: cookieHeader,
      'Content-Type': 'application/json',
    },
  });

  if (!getRes.ok) {
    console.error('Failed to load task:', getRes.status, await getRes.text());
    process.exit(1);
  }

  const payload = await getRes.json();
  const task = payload.tasks?.[0];
  if (!task) {
    console.error('Task not found:', taskId);
    process.exit(1);
  }

  task.status = status;

  const saveRes = await fetch(`${API_URL}/tasks`, {
    method: 'POST',
    headers: {
      Cookie: cookieHeader,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ task }),
  });

  if (!saveRes.ok) {
    console.error('Failed to update task status:', saveRes.status, await saveRes.text());
    process.exit(1);
  }

  console.log(`Updated task ${taskId} to status '${status}'`);
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
