import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import {
  getPlatformSettings,
  savePlatformSettings,
  createAuditLog,
} from '@server/services/admin.service';
import { ForbiddenError } from '@server/errors';

function maskKey(key: unknown): string | undefined {
  if (!key || typeof key !== 'string' || key.length === 0) return undefined;
  return key.length > 8 ? key.slice(0, 4) + '...' + key.slice(-4) : '****';
}

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }
    const raw = await getPlatformSettings();
    const settings: Record<string, unknown> = { ...raw };

    const openaiKey = raw.openai_api_key as string | undefined;
    delete settings.openai_api_key;
    const openaiHint = maskKey(openaiKey);
    if (openaiHint) settings.openai_key_hint = openaiHint;

    const stripeSecretKey = raw.stripe_secret_key as string | undefined;
    delete settings.stripe_secret_key;
    const stripeSecretHint = maskKey(stripeSecretKey);
    if (stripeSecretHint) settings.stripe_secret_key_hint = stripeSecretHint;

    const stripePubKey = raw.stripe_publishable_key as string | undefined;
    delete settings.stripe_publishable_key;
    const stripePubHint = maskKey(stripePubKey);
    if (stripePubHint) settings.stripe_publishable_key_hint = stripePubHint;

    return NextResponse.json({ settings });
  })
);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin') {
      throw new ForbiddenError();
    }
    const body = await req.json();
    await savePlatformSettings(body.settings ?? {}, req.session.userId);
    await createAuditLog({
      actorId: req.session.userId,
      actorEmail: req.session.email,
      actorType: 'admin',
      action: 'Updated platform settings',
      resource: 'platform_settings',
      severity: 'info',
      metadata: { changedKeys: Object.keys(body.settings ?? {}) },
    });
    const raw = await getPlatformSettings();
    const settings: Record<string, unknown> = { ...raw };

    const openaiKey = raw.openai_api_key as string | undefined;
    delete settings.openai_api_key;
    const openaiHint = maskKey(openaiKey);
    if (openaiHint) settings.openai_key_hint = openaiHint;

    const stripeSecretKey = raw.stripe_secret_key as string | undefined;
    delete settings.stripe_secret_key;
    const stripeSecretHint = maskKey(stripeSecretKey);
    if (stripeSecretHint) settings.stripe_secret_key_hint = stripeSecretHint;

    const stripePubKey = raw.stripe_publishable_key as string | undefined;
    delete settings.stripe_publishable_key;
    const stripePubHint = maskKey(stripePubKey);
    if (stripePubHint) settings.stripe_publishable_key_hint = stripePubHint;

    return NextResponse.json({ settings });
  })
);
