/**
 * F162 Phase B: Lark Golden Chain E2E test.
 *
 * Hits real lark-cli + real Feishu. Skipped unless LARK_E2E=1.
 *
 * Pre-requisite: `lark-cli auth login --recommend --domain all` must have run
 * successfully. Scope must cover docx/base/task/calendar/slides at minimum.
 *
 * Usage:
 *   LARK_E2E=1 node --test packages/api/test/infrastructure/lark-e2e-golden-chain.test.js
 *
 * Cleanup policy (idempotent runs > demo persistence):
 *   - Default: auto-cleanup after assertions (drive +delete for docx/base/slides,
 *     task +complete for tasks). Keeps the tenant free of F162-B test artifacts.
 *   - KEEP_ARTIFACTS=1: skip cleanup so URLs stay live for demo / visual verification.
 *   - Calendar events: lark-cli v1.x has no +delete verb — always logged as "not
 *     cleaned; event auto-expires 1h later" (acceptable since the event is 24h out
 *     with 1h duration and will age off visually).
 *   - Each delete wraps in try/catch; partial cleanup never fails the test body.
 */

import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { describe, it } from 'node:test';
import { promisify } from 'node:util';

const execFileAsync = promisify(execFile);

function noopLog() {
  const noop = () => {};
  const log = { info: noop, warn: noop, error: noop, debug: noop, trace: noop, fatal: noop, child: () => noopLog() };
  return log;
}

const { LarkCliExecutor } = await import('../../dist/infrastructure/enterprise/LarkCliExecutor.js');
const { LarkActionService } = await import('../../dist/infrastructure/enterprise/LarkActionService.js');

const enabled = process.env.LARK_E2E === '1';
const keepArtifacts = process.env.KEEP_ARTIFACTS === '1';

async function bestEffortDelete(args, label) {
  try {
    await execFileAsync('lark-cli', args, { timeout: 30_000 });
    // eslint-disable-next-line no-console
    console.log(`  ✓ cleaned ${label}`);
  } catch (err) {
    // eslint-disable-next-line no-console
    console.warn(`  ⚠ cleanup skipped for ${label}: ${err.message?.slice(0, 120)}`);
  }
}

async function cleanup(result) {
  // eslint-disable-next-line no-console
  console.log('\n--- F162-B E2E cleanup (default; set KEEP_ARTIFACTS=1 to preserve) ---');

  await bestEffortDelete(
    ['drive', '+delete', '--type', 'docx', '--file-token', result.doc.documentId, '--yes'],
    `docx ${result.doc.documentId}`,
  );
  await bestEffortDelete(
    ['drive', '+delete', '--type', 'bitable', '--file-token', result.base.appToken, '--yes'],
    `bitable ${result.base.appToken}`,
  );
  for (const task of result.tasks) {
    await bestEffortDelete(['task', '+complete', '--task-id', task.guid], `task ${task.guid}`);
  }
  if (result.slides) {
    await bestEffortDelete(
      ['drive', '+delete', '--type', 'slides', '--file-token', result.slides.presentationId, '--yes'],
      `slides ${result.slides.presentationId}`,
    );
  }
  // eslint-disable-next-line no-console
  console.log(`  ℹ calendar event ${result.calendarEvent.eventId} left in place (lark-cli v1.x has no +delete)`);
}

describe('F162 Phase B: Lark Golden Chain (real CLI)', { skip: !enabled }, () => {
  it('creates doc + base + task + calendar event + slides and returns all URLs', async () => {
    const executor = new LarkCliExecutor(noopLog(), 60_000);
    const service = new LarkActionService(executor, noopLog());

    const available = await service.isAvailable();
    assert.ok(available, 'lark-cli must be installed');

    const ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
    const myOpenId = process.env.LARK_MY_OPEN_ID;
    assert.ok(myOpenId, 'LARK_MY_OPEN_ID env var required (your ou_xxx)');

    const now = Date.now();
    const startIso = new Date(now + 24 * 3600 * 1000).toISOString();
    const endIso = new Date(now + 25 * 3600 * 1000).toISOString();

    const result = await service.goldenChain({
      docTitle: `F162-B E2E Doc ${ts}`,
      docMarkdown: `# F162 Phase B E2E\n\nAuto-generated by LarkActionService golden chain at ${ts}.`,
      baseName: `F162-B E2E Base ${ts}`,
      tasks: [
        {
          summary: `F162-B E2E Task 1 ${ts}`,
          assigneeOpenId: myOpenId,
          description: 'Created by goldenChain',
        },
      ],
      calendarSummary: `F162-B E2E Event ${ts}`,
      calendarStart: startIso,
      calendarEnd: endIso,
      calendarAttendeeOpenIds: [myOpenId],
      includeSlides: true,
    });

    // eslint-disable-next-line no-console
    console.log('\n=== F162-B Golden Chain Result ===');
    // eslint-disable-next-line no-console
    console.log(result.summary);
    // eslint-disable-next-line no-console
    console.log('================================\n');

    try {
      assert.ok(result.doc.documentId.length > 0);
      assert.ok(result.doc.url.startsWith('https://'));
      assert.ok(result.base.appToken.length > 0);
      assert.ok(result.base.url.startsWith('https://'));
      assert.equal(result.tasks.length, 1);
      assert.ok(result.tasks[0].guid.length > 0);
      assert.ok(result.calendarEvent.eventId.length > 0);
      if (result.slides) {
        assert.ok(result.slides.presentationId.length > 0);
        assert.ok(result.slides.url.startsWith('https://'));
      }
      assert.ok(result.summary.includes('文档'));
      assert.ok(result.summary.includes('多维表'));
      assert.ok(result.summary.includes('任务'));
      assert.ok(result.summary.includes('日程'));
    } finally {
      if (keepArtifacts) {
        // eslint-disable-next-line no-console
        console.log('\nKEEP_ARTIFACTS=1 — skipping cleanup. URLs above stay live.');
      } else {
        await cleanup(result);
      }
    }
  });
});
