import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'

let mockLoadConfig: ReturnType<typeof vi.fn>
let mockSaveConfig: ReturnType<typeof vi.fn>
let mockOutput: ReturnType<typeof vi.fn>
let mockOutputError: ReturnType<typeof vi.fn>
let mockSpawnSync: ReturnType<typeof vi.fn>

beforeEach(() => {
  mockLoadConfig = vi.fn(() => ({
    mode: 'remote',
    apiUrl: 'https://flowy-ai.fly.dev/graphql',
    apiKey: '',
    client: { name: '' },
    projects: {},
  }))
  mockSaveConfig = vi.fn()
  mockOutput = vi.fn()
  mockOutputError = vi.fn()
  mockSpawnSync = vi.fn()

  vi.doMock('../util/config.ts', async () => {
    const actual =
      await vi.importActual<typeof import('../util/config.ts')>(
        '../util/config.ts',
      )
    return {
      loadConfig: mockLoadConfig,
      saveConfig: mockSaveConfig,
      fingerprintKey: actual.fingerprintKey,
    }
  })

  vi.doMock('../util/format.ts', () => ({
    output: mockOutput,
    outputError: mockOutputError,
  }))

  vi.doMock('node:child_process', () => ({
    spawnSync: mockSpawnSync,
  }))
})

afterEach(() => {
  vi.resetModules()
  vi.restoreAllMocks()
})

describe('setup command', () => {
  test('exports a command named "setup"', async () => {
    const { setupCommand } = await import('./setup.ts')
    expect(setupCommand.name()).toBe('setup')
  })

  test('has local and remote subcommands', async () => {
    const { setupCommand } = await import('./setup.ts')
    const subcommandNames = setupCommand.commands.map((c) => c.name())
    expect(subcommandNames).toContain('local')
    expect(subcommandNames).toContain('remote')
    expect(setupCommand.commands).toHaveLength(2)
  })

  test('setup local installs the pinned package version (no docker)', async () => {
    mockSpawnSync.mockReturnValue({ status: 0 })

    const { setupCommand } = await import('./setup.ts')
    const { pinnedInstallSpec } = await import('./serve.ts')
    await setupCommand.parseAsync(['local'], { from: 'user' })

    // installs the package pinned to the exact CLI version
    expect(mockSpawnSync).toHaveBeenCalledWith(
      'bun',
      ['add', pinnedInstallSpec()],
      expect.anything(),
    )
    // never shells out to docker
    expect(mockSpawnSync.mock.calls.some((call) => call[0] === 'docker')).toBe(
      false,
    )
  })

  test('setup local saves config with mode "local" and apiUrl on success', async () => {
    mockSpawnSync.mockReturnValue({ status: 0 })

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(['local'], { from: 'user' })

    expect(mockSaveConfig).toHaveBeenCalledWith(
      expect.objectContaining({
        mode: 'local',
        apiUrl: 'http://localhost:4000/graphql',
      }),
    )
  })

  test('setup remote requires --email', async () => {
    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(['remote'], { from: 'user' })

    expect(mockOutputError).toHaveBeenCalledWith(
      expect.objectContaining({
        message: expect.stringContaining('--email is required'),
      }),
    )
  })

  test('setup remote registers without --tier (tier is optional)', async () => {
    const mockGraphql = vi.fn().mockResolvedValue({
      register: {
        user: {
          id: 'user_1',
          email: 'test@example.com',
          tier: null,
          createdAt: '2026-06-13T00:00:00Z',
          graceEndsAt: null,
        },
        apiKey: 'flowy_key',
        checkoutUrl: null,
      },
    })
    vi.doMock('../util/client.ts', () => ({
      graphql: mockGraphql,
    }))
    mockSpawnSync.mockReturnValue({ status: 0, stdout: Buffer.from('') })

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(['remote', '--email', 'test@example.com'], {
      from: 'user',
    })

    // No tier required: registration proceeds, no usage error raised.
    expect(mockOutputError).not.toHaveBeenCalled()
    expect(mockGraphql).toHaveBeenCalledOnce()
    const [, variables] = mockGraphql.mock.calls[0]!
    expect(variables).toEqual({ email: 'test@example.com', tier: undefined })
    expect(mockSaveConfig).toHaveBeenCalledWith(
      expect.objectContaining({ mode: 'remote', apiKey: 'flowy_key' }),
    )
  })

  test('setup remote outputs error when registration fails', async () => {
    const mockGraphql = vi
      .fn()
      .mockRejectedValue(new Error('Registration is temporarily closed.'))
    vi.doMock('../util/client.ts', () => ({
      graphql: mockGraphql,
    }))

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(
      ['remote', '--email', 'test@example.com', '--tier', 'explorer'],
      { from: 'user' },
    )

    expect(mockOutputError).toHaveBeenCalledWith(
      expect.objectContaining({
        message: 'Registration is temporarily closed.',
      }),
    )
    expect(mockSaveConfig).toHaveBeenCalledTimes(1)
    expect(mockSaveConfig).toHaveBeenCalledWith(
      expect.objectContaining({
        mode: 'remote',
        apiUrl: 'https://flowy-ai.fly.dev/graphql',
      }),
    )
  })

  test('setup remote sends correct email and tier in mutation', async () => {
    const mockGraphql = vi.fn().mockResolvedValue({
      register: {
        user: {
          id: 'user_1',
          email: 'a@b.com',
          tier: 'pro',
          createdAt: '2026-01-01T00:00:00Z',
          graceEndsAt: null,
        },
        apiKey: 'flowy_key',
        checkoutUrl: null,
      },
    })
    vi.doMock('../util/client.ts', () => ({
      graphql: mockGraphql,
    }))
    mockSpawnSync.mockReturnValue({
      status: 0,
      stdout: Buffer.from(''),
    })

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(
      ['remote', '--email', 'a@b.com', '--tier', 'pro'],
      { from: 'user' },
    )

    expect(mockGraphql).toHaveBeenCalledOnce()
    const [, variables] = mockGraphql.mock.calls[0]!
    expect(variables).toEqual({ email: 'a@b.com', tier: 'pro' })
  })

  test('setup remote registers, saves API key, and outputs result', async () => {
    const mockGraphql = vi.fn().mockResolvedValue({
      register: {
        user: {
          id: 'user_1',
          email: 'test@example.com',
          tier: 'explorer',
          createdAt: '2026-03-30T00:00:00Z',
          graceEndsAt: '2026-04-13T00:00:00Z',
        },
        apiKey: 'flowy_test_key_123',
        checkoutUrl: 'https://checkout.stripe.com/session_123',
      },
    })
    vi.doMock('../util/client.ts', () => ({
      graphql: mockGraphql,
    }))
    mockSpawnSync.mockReturnValue({
      status: 0,
      stdout: Buffer.from(''),
    })

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(
      ['remote', '--email', 'test@example.com', '--tier', 'explorer'],
      { from: 'user' },
    )

    expect(mockGraphql).toHaveBeenCalledWith(
      expect.stringContaining('register(email: $email, tier: $tier)'),
      { email: 'test@example.com', tier: 'explorer' },
    )
    expect(mockSaveConfig).toHaveBeenCalledWith(
      expect.objectContaining({
        mode: 'remote',
        apiKey: 'flowy_test_key_123',
      }),
    )
    // Default output surfaces a fingerprint, never the raw secret (F35).
    const outputArg = mockOutput.mock.calls[0]![0]
    expect(JSON.stringify(outputArg)).not.toContain('flowy_test_key_123')
    expect(outputArg).toEqual(
      expect.objectContaining({
        user: expect.objectContaining({
          email: 'test@example.com',
          tier: 'explorer',
          graceEndsAt: '2026-04-13T00:00:00Z',
        }),
        keyFingerprint: expect.stringMatching(/sha256:[0-9a-f]{12}/),
        checkoutUrl: 'https://checkout.stripe.com/session_123',
      }),
    )
    expect(outputArg).not.toHaveProperty('apiKey')
  })

  test('setup remote --show-key reveals the full API key', async () => {
    const mockGraphql = vi.fn().mockResolvedValue({
      register: {
        user: {
          id: 'user_1',
          email: 'test@example.com',
          tier: 'explorer',
          createdAt: '2026-03-30T00:00:00Z',
          graceEndsAt: null,
        },
        apiKey: 'flowy_test_key_123',
        checkoutUrl: null,
      },
    })
    vi.doMock('../util/client.ts', () => ({
      graphql: mockGraphql,
    }))
    mockSpawnSync.mockReturnValue({ status: 0, stdout: Buffer.from('') })

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(
      ['remote', '--email', 'test@example.com', '--show-key'],
      { from: 'user' },
    )

    expect(mockOutput).toHaveBeenCalledWith(
      expect.objectContaining({ apiKey: 'flowy_test_key_123' }),
    )
  })

  test('setup local warns when the skill install fails', async () => {
    // bun add succeeds, npx skills add fails (non-zero status).
    mockSpawnSync.mockImplementation((cmd: string) =>
      cmd === 'npx' ? { status: 1 } : { status: 0 },
    )
    const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(['local'], { from: 'user' })

    const warned = errSpy.mock.calls.map((c) => String(c[0])).join('\n')
    expect(warned).toMatch(/skill/i)
    expect(warned).toContain('npx skills add sqaoss/flowy')
    // Setup itself still completes successfully (config saved, result emitted).
    expect(mockOutput).toHaveBeenCalled()
    expect(mockOutputError).not.toHaveBeenCalled()
    errSpy.mockRestore()
  })

  test('setup local does not warn when the skill install succeeds', async () => {
    mockSpawnSync.mockReturnValue({ status: 0 })
    const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(['local'], { from: 'user' })

    const warned = errSpy.mock.calls.map((c) => String(c[0])).join('\n')
    expect(warned).not.toMatch(/skill/i)
    errSpy.mockRestore()
  })

  test('setup remote persists the API key before any later step (save-after-register)', async () => {
    const mockGraphql = vi.fn().mockResolvedValue({
      register: {
        user: {
          id: 'user_1',
          email: 'a@b.com',
          tier: null,
          createdAt: '2026-06-13T00:00:00Z',
          graceEndsAt: null,
        },
        apiKey: 'flowy_key_persisted',
        checkoutUrl: null,
      },
    })
    vi.doMock('../util/client.ts', () => ({ graphql: mockGraphql }))

    // The skill install (a step AFTER the key is obtained) blows up hard.
    // The key must already be on disk by then so the user is never stranded.
    let keySavedBeforeSkillInstall = false
    mockSaveConfig.mockImplementation((cfg: { apiKey?: string }) => {
      if (cfg.apiKey === 'flowy_key_persisted')
        keySavedBeforeSkillInstall = true
    })
    mockSpawnSync.mockImplementation((cmd: string) => {
      if (cmd === 'npx') {
        // By the time the (post-register) skill install runs, the key is saved.
        expect(keySavedBeforeSkillInstall).toBe(true)
        throw new Error('npx exploded')
      }
      return { status: 0, stdout: Buffer.from('') }
    })
    const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(['remote', '--email', 'a@b.com'], {
      from: 'user',
    })

    // The key was saved at least once with the real value before the failure.
    expect(
      mockSaveConfig.mock.calls.some(
        (c) => (c[0] as { apiKey?: string }).apiKey === 'flowy_key_persisted',
      ),
    ).toBe(true)
    errSpy.mockRestore()
  })

  test('setup remote warns when the skill install fails', async () => {
    const mockGraphql = vi.fn().mockResolvedValue({
      register: {
        user: {
          id: 'user_1',
          email: 'a@b.com',
          tier: null,
          createdAt: '2026-06-13T00:00:00Z',
          graceEndsAt: null,
        },
        apiKey: 'flowy_key',
        checkoutUrl: null,
      },
    })
    vi.doMock('../util/client.ts', () => ({ graphql: mockGraphql }))
    mockSpawnSync.mockImplementation((cmd: string) =>
      cmd === 'npx' ? { status: 1 } : { status: 0 },
    )
    const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})

    const { setupCommand } = await import('./setup.ts')
    await setupCommand.parseAsync(['remote', '--email', 'a@b.com'], {
      from: 'user',
    })

    const warned = errSpy.mock.calls.map((c) => String(c[0])).join('\n')
    expect(warned).toMatch(/skill/i)
    expect(warned).toContain('npx skills add sqaoss/flowy')
    expect(mockOutput).toHaveBeenCalled()
    expect(mockOutputError).not.toHaveBeenCalled()
    errSpy.mockRestore()
  })
})
