/**
 * Tests for GET/PUT /api/settings/kill-switch
 */

import { describe, it, expect, vi, beforeEach } from 'vitest';

const mockListFlags = vi.fn();
const mockCreateFlag = vi.fn();
const mockUpdateFlag = vi.fn();
vi.mock('@/lib/platform-client', () => ({
  listFlags: (...args: unknown[]) => mockListFlags(...args),
  createFlag: (...args: unknown[]) => mockCreateFlag(...args),
  updateFlag: (...args: unknown[]) => mockUpdateFlag(...args),
}));

import { GET, PUT } from '@/app/api/settings/kill-switch/route';

async function makeGet() {
  return GET();
}

async function makePut(body: object) {
  const { NextRequest } = await import('next/server');
  return PUT(
    new NextRequest(
      new Request('http://localhost:3001/api/settings/kill-switch', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
    )
  );
}

describe('GET /api/settings/kill-switch', () => {
  beforeEach(() => vi.clearAllMocks());

  it('returns default state when no kill_switch flag exists', async () => {
    mockListFlags.mockResolvedValue({ flags: [] });

    const res = await makeGet();
    expect(res.status).toBe(200);
    const data = await res.json();

    expect(data.enabled).toBe(false);
    expect(data.platforms.desktop).toBe(true);
    expect(data.platforms.ios).toBe(true);
    expect(data.platforms.android).toBe(true);
    expect(data.platforms.web).toBe(true);
    expect(data.reason).toBe('');
  });

  it('returns existing kill_switch flag state', async () => {
    mockListFlags.mockResolvedValue({
      flags: [
        {
          key: 'kill_switch',
          enabled: true,
          platforms: ['desktop', 'ios'],
          description: 'Maintenance window',
          updatedAt: '2026-02-16T00:00:00Z',
        },
      ],
    });

    const res = await makeGet();
    const data = await res.json();

    expect(data.enabled).toBe(true);
    expect(data.platforms.desktop).toBe(true);
    expect(data.platforms.ios).toBe(true);
    expect(data.platforms.android).toBe(false);
    expect(data.platforms.web).toBe(false);
    expect(data.reason).toBe('Maintenance window');
  });

  it('maps empty platforms array to all-true', async () => {
    mockListFlags.mockResolvedValue({
      flags: [{ key: 'kill_switch', enabled: true, platforms: [] }],
    });

    const res = await makeGet();
    const data = await res.json();
    expect(data.platforms.desktop).toBe(true);
    expect(data.platforms.ios).toBe(true);
  });

  it('returns 500 on error', async () => {
    mockListFlags.mockRejectedValue(new Error('Service down'));

    const res = await makeGet();
    expect(res.status).toBe(500);
    const data = await res.json();
    expect(data.error).toContain('kill switch');
  });
});

describe('PUT /api/settings/kill-switch', () => {
  beforeEach(() => vi.clearAllMocks());

  it('updates existing kill_switch flag', async () => {
    mockListFlags.mockResolvedValue({
      flags: [{ key: 'kill_switch', id: 'flag-123', enabled: false }],
    });
    mockUpdateFlag.mockResolvedValue({
      enabled: true,
      platforms: [],
      description: 'Emergency shutdown',
      updatedAt: '2026-02-16T10:00:00Z',
    });

    const res = await makePut({ enabled: true, reason: 'Emergency shutdown' });
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.enabled).toBe(true);
    expect(data.reason).toBe('Emergency shutdown');
  });

  it('creates new kill_switch flag when none exists', async () => {
    mockListFlags.mockResolvedValue({ flags: [] });
    mockCreateFlag.mockResolvedValue({
      key: 'kill_switch',
      enabled: true,
      platforms: ['desktop'],
      description: 'Test',
      updatedAt: '2026-02-16T10:00:00Z',
    });

    const res = await makePut({
      enabled: true,
      reason: 'Test',
      platforms: { desktop: true, ios: false, android: false, web: false },
    });
    expect(res.status).toBe(200);
    expect(mockCreateFlag).toHaveBeenCalled();
  });

  it('returns 500 on error', async () => {
    mockListFlags.mockRejectedValue(new Error('Network error'));

    const res = await makePut({ enabled: false });
    expect(res.status).toBe(500);
  });

  it('defaults enabled to false when not provided', async () => {
    mockListFlags.mockResolvedValue({ flags: [] });
    mockCreateFlag.mockResolvedValue({
      key: 'kill_switch',
      enabled: false,
      platforms: [],
      updatedAt: '2026-02-16T10:00:00Z',
    });

    const res = await makePut({});
    const data = await res.json();
    expect(data.enabled).toBe(false);
  });
});
