/**
 * Platform Settings API — persists admin-configurable settings to Cosmos DB.
 *
 * GET  /api/settings/platform  → current settings
 * PUT  /api/settings/platform  → update settings
 *
 * Stored in the `settings` container with id=platform_config, userId=_system.
 */

import { NextRequest, NextResponse } from 'next/server';
import { getCollection } from '@/lib/datastore';
import { requireAdmin } from '@/lib/auth-server';
import { logError } from '@/lib/logger';
import type { DocumentCollection } from '@bytelyst/datastore';

// Settings docs use userId as partition key and don't have a productId field
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function settingsCollection(): DocumentCollection<any> {
  return getCollection('settings', '/userId');
}

const SETTINGS_ID = 'platform_config';
const PARTITION_KEY = '_system';

interface PlatformSettings {
  id: string;
  userId: string;
  platformName: string;
  supportEmail: string;
  defaultLanguage: string;
  maintenanceMode: boolean;
  allowSelfRegistration: boolean;
  rateLimits: {
    globalPerMin: number;
    perUserPerMin: number;
    maxTokenBurst: number;
    abuseThreshold: number;
    autoSuspendOnAbuse: boolean;
    ipBlocklist: boolean;
  };
  notifications: {
    newUserSignup: boolean;
    usageThreshold: boolean;
    failedPayment: boolean;
    securityAlerts: boolean;
  };
  dataRetentionDays: number;
  backupFrequency: string;
  auditLogging: boolean;
  updatedAt: string;
  updatedBy: string;
}

const DEFAULTS: PlatformSettings = {
  id: SETTINGS_ID,
  userId: PARTITION_KEY,
  platformName: '',
  supportEmail: '',
  defaultLanguage: 'en-US',
  maintenanceMode: false,
  allowSelfRegistration: true,
  rateLimits: {
    globalPerMin: 1000,
    perUserPerMin: 60,
    maxTokenBurst: 4096,
    abuseThreshold: 50,
    autoSuspendOnAbuse: true,
    ipBlocklist: true,
  },
  notifications: {
    newUserSignup: true,
    usageThreshold: true,
    failedPayment: true,
    securityAlerts: true,
  },
  dataRetentionDays: 365,
  backupFrequency: 'daily',
  auditLogging: true,
  updatedAt: new Date().toISOString(),
  updatedBy: 'system',
};

export async function GET(req: NextRequest) {
  try {
    const admin = await requireAdmin(req);
    if (!admin) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const settings = await settingsCollection().findById(SETTINGS_ID, PARTITION_KEY);
    if (settings) return NextResponse.json(settings);
    return NextResponse.json(DEFAULTS);
  } catch (error) {
    logError('Platform settings GET error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

export async function PUT(req: NextRequest) {
  try {
    const admin = await requireAdmin(req);
    if (!admin) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const body = await req.json();

    const existingDoc = await settingsCollection().findById(SETTINGS_ID, PARTITION_KEY);
    const existing: PlatformSettings = (existingDoc as PlatformSettings) ?? DEFAULTS;

    const updated: PlatformSettings = {
      ...existing,
      platformName: body.platformName ?? existing.platformName,
      supportEmail: body.supportEmail ?? existing.supportEmail,
      defaultLanguage: body.defaultLanguage ?? existing.defaultLanguage,
      maintenanceMode: body.maintenanceMode ?? existing.maintenanceMode,
      allowSelfRegistration: body.allowSelfRegistration ?? existing.allowSelfRegistration,
      rateLimits: { ...existing.rateLimits, ...(body.rateLimits ?? {}) },
      notifications: { ...existing.notifications, ...(body.notifications ?? {}) },
      dataRetentionDays: body.dataRetentionDays ?? existing.dataRetentionDays,
      backupFrequency: body.backupFrequency ?? existing.backupFrequency,
      auditLogging: body.auditLogging ?? existing.auditLogging,
      updatedAt: new Date().toISOString(),
      updatedBy: admin.email ?? 'admin',
    };

    await settingsCollection().upsert(updated);
    return NextResponse.json(updated);
  } catch (error) {
    logError('Platform settings PUT error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
