/**
 * Kill Switch API — proxies to platform-service feature flags module.
 *
 * GET  /api/settings/kill-switch  → { enabled, platforms, reason, updatedAt, updatedBy }
 * PUT  /api/settings/kill-switch  → body: { enabled?, platforms?, reason? }
 *
 * Maps the kill_switch feature flag to the legacy per-platform format.
 * The flag's `enabled` field = master switch, `platforms` array = which platforms are affected,
 * and `description` field stores the reason.
 */

import { NextRequest, NextResponse } from 'next/server';
import { listFlags, createFlag, updateFlag } from '@/lib/platform-client';

const FLAG_KEY = 'kill_switch';
const ALL_PLATFORMS = ['desktop', 'ios', 'android', 'web'];

interface PlatformFlags {
  desktop: boolean;
  ios: boolean;
  android: boolean;
  web: boolean;
}

function flagToPlatforms(flagPlatforms: string[]): PlatformFlags {
  if (flagPlatforms.length === 0) {
    return { desktop: true, ios: true, android: true, web: true };
  }
  return {
    desktop: flagPlatforms.includes('desktop'),
    ios: flagPlatforms.includes('ios'),
    android: flagPlatforms.includes('android'),
    web: flagPlatforms.includes('web'),
  };
}

function platformsToArray(platforms: PlatformFlags): string[] {
  const arr = ALL_PLATFORMS.filter(p => platforms[p as keyof PlatformFlags]);
  return arr.length === ALL_PLATFORMS.length ? [] : arr;
}

export async function GET() {
  try {
    const result = await listFlags();
    const flag = (result.flags ?? []).find(f => f.key === FLAG_KEY);

    if (!flag) {
      return NextResponse.json({
        enabled: false,
        platforms: { desktop: true, ios: true, android: true, web: true },
        reason: '',
        updatedAt: new Date().toISOString(),
        updatedBy: 'system',
      });
    }

    return NextResponse.json({
      enabled: flag.enabled,
      platforms: flagToPlatforms(flag.platforms ?? []),
      reason: flag.description ?? '',
      updatedAt: flag.updatedAt,
      updatedBy: 'admin',
    });
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to read kill switch', details: String(error) },
      { status: 500 }
    );
  }
}

export async function PUT(req: NextRequest) {
  try {
    const body = await req.json();
    const enabled = typeof body.enabled === 'boolean' ? body.enabled : false;
    const reason = typeof body.reason === 'string' ? body.reason : '';

    const platforms: PlatformFlags = body.platforms ?? {
      desktop: true,
      ios: true,
      android: true,
      web: true,
    };

    const result = await listFlags();
    const existing = (result.flags ?? []).find(f => f.key === FLAG_KEY);

    if (existing) {
      const updated = await updateFlag(existing.id, {
        enabled,
        description: reason,
        platforms: platformsToArray(platforms),
      });
      return NextResponse.json({
        enabled: updated.enabled,
        platforms: flagToPlatforms(updated.platforms ?? []),
        reason: updated.description ?? '',
        updatedAt: updated.updatedAt,
        updatedBy: body.updatedBy ?? 'admin',
      });
    }

    const created = await createFlag({
      key: FLAG_KEY,
      enabled,
      description: reason,
      platforms: platformsToArray(platforms),
      segments: [],
      percentage: 100,
    });
    return NextResponse.json({
      enabled: created.enabled,
      platforms: flagToPlatforms(created.platforms ?? []),
      reason: created.description ?? '',
      updatedAt: created.updatedAt,
      updatedBy: body.updatedBy ?? 'admin',
    });
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to update kill switch', details: String(error) },
      { status: 500 }
    );
  }
}
