import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { config } from '../../../config.js';
import { createInMemoryClient } from '../../../test/mcpServer.js';

function firstText(result: unknown): string {
  const r = result as { content?: Array<{ text?: string }> } | undefined;
  return r?.content?.[0]?.text ?? '';
}

describe('generate_component Vue SFC', () => {
  let tmpDir: string;
  let previousRoot: string;

  beforeEach(() => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-dev-mcp-vue-'));
    previousRoot = config.workspaceRoot;
    (config as { workspaceRoot: string }).workspaceRoot = tmpDir;
  });

  afterEach(() => {
    (config as { workspaceRoot: string }).workspaceRoot = previousRoot;
    fs.rmSync(tmpDir, { recursive: true, force: true });
  });

  it('writes a .vue SFC for Vue projects', async () => {
    fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ dependencies: { vue: '^3.0' } }));
    fs.writeFileSync(path.join(tmpDir, 'tsconfig.json'), '{}');

    const client = await createInMemoryClient();
    const result = await client.callTool({
      name: 'generate_component',
      arguments: { name: 'UserCard', style: 'css-module' },
    });
    const payload = JSON.parse(firstText(result)) as { kind: string; files: string[] };
    expect(payload.kind).toBe('vue');
    expect(payload.files.some((f) => f.endsWith('UserCard.vue'))).toBe(true);
    const vue = fs.readFileSync(payload.files[0]!, 'utf8');
    expect(vue).toContain('<script setup lang="ts">');
    expect(vue).toContain('<template>');
    expect(vue).toContain('UserCard');
  });

  it('writes a .vue SFC for Nuxt projects', async () => {
    fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ dependencies: { nuxt: '^3.0' } }));
    fs.writeFileSync(path.join(tmpDir, 'nuxt.config.ts'), 'export default {}\n');

    const client = await createInMemoryClient();
    const result = await client.callTool({
      name: 'generate_component',
      arguments: { name: 'HeroBanner', style: 'none' },
    });
    const payload = JSON.parse(firstText(result)) as { kind: string; files: string[] };
    expect(payload.kind).toBe('nuxt');
    expect(fs.existsSync(payload.files[0]!)).toBe(true);
  });
});
