/**
 * Staff System Settings API
 *
 * GET /api/staff/settings - List all settings (masked)
 * POST /api/staff/settings - Create or update a setting
 * DELETE /api/staff/settings - Delete a setting
 *
 * Only accessible to ADMIN and SUPER_ADMIN staff.
 */

import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import {
  systemSettingsService,
  SETTING_KEYS,
} from "@/lib/services/system-settings.service";
import { logger } from "@/lib/logger";
import { z } from "zod";
// Convex routing (WU-13): systemSettingsService encapsulates its own Prisma queries. Needs service migration.

// Validation schemas
const createSettingSchema = z.object({
  key: z.string().min(1).max(100),
  value: z.string().min(1).max(10000),
  description: z.string().max(500).optional(),
  category: z
    .enum([
      "n8n",
      "whatsapp",
      "elevenlabs",
      "integrations",
      "security",
      "general",
    ])
    .optional(),
});

const deleteSettingSchema = z.object({
  key: z.string().min(1).max(100),
});

// Quick-setup templates for common settings
const SETTING_TEMPLATES = {
  n8n: [
    {
      key: SETTING_KEYS.N8N_WEBHOOK_AUTH_TOKEN,
      description: "Authentication token for N8N webhook callbacks",
      category: "n8n",
    },
    {
      key: SETTING_KEYS.N8N_BASE_URL,
      description:
        "Base URL of your N8N instance (e.g., https://n8n.example.com)",
      category: "n8n",
    },
    {
      key: SETTING_KEYS.N8N_API_KEY,
      description: "N8N API key for workflow management",
      category: "n8n",
    },
  ],
  whatsapp: [
    {
      key: SETTING_KEYS.WHATSAPP_APP_SECRET,
      description: "Meta WhatsApp App Secret for webhook verification",
      category: "whatsapp",
    },
    {
      key: SETTING_KEYS.WHATSAPP_VERIFY_TOKEN,
      description: "Token for Meta webhook URL verification",
      category: "whatsapp",
    },
  ],
  elevenlabs: [
    {
      key: SETTING_KEYS.ELEVENLABS_API_KEY,
      description: "ElevenLabs API key for voice agent provisioning",
      category: "elevenlabs",
    },
  ],
};

/**
 * GET /api/staff/settings
 * List all settings or by category
 */
export async function GET(request: NextRequest) {
  try {
    // Validate staff session (admin only)
    const session = await validateStaffSession(request);
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    if (session.role !== "ADMIN" && session.role !== "SUPER_ADMIN") {
      return NextResponse.json(
        { error: "Admin access required" },
        { status: 403 },
      );
    }

    const category = request.nextUrl.searchParams.get("category");

    let settings;
    if (category) {
      settings = await systemSettingsService.getByCategory(category);
    } else {
      settings = await systemSettingsService.getAll();
    }

    return NextResponse.json({
      success: true,
      settings,
      templates: SETTING_TEMPLATES,
      availableKeys: SETTING_KEYS,
    });
  } catch (error) {
    logger.error("Failed to get settings", { error });
    return NextResponse.json(
      { success: false, error: "Failed to load settings" },
      { status: 500 },
    );
  }
}

/**
 * POST /api/staff/settings
 * Create or update a setting
 */
export async function POST(request: NextRequest) {
  try {
    // Validate staff session (admin only)
    const session = await validateStaffSession(request);
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    if (session.role !== "ADMIN" && session.role !== "SUPER_ADMIN") {
      return NextResponse.json(
        { error: "Admin access required" },
        { status: 403 },
      );
    }

    const body = await request.json();
    const validationResult = createSettingSchema.safeParse(body);

    if (!validationResult.success) {
      return NextResponse.json(
        {
          success: false,
          error: "Invalid request: " + validationResult.error.errors[0].message,
        },
        { status: 400 },
      );
    }

    const { key, value, description, category } = validationResult.data;

    const success = await systemSettingsService.set(key, value, {
      description,
      category,
      updatedBy: session.staffId,
    });

    if (!success) {
      return NextResponse.json(
        { success: false, error: "Failed to save setting" },
        { status: 500 },
      );
    }

    logger.info("Setting updated by staff", {
      key,
      staffId: session.staffId,
      staffRole: session.role,
    });

    return NextResponse.json({
      success: true,
      message: `Setting "${key}" saved successfully`,
    });
  } catch (error) {
    logger.error("Failed to save setting", { error });
    return NextResponse.json(
      { success: false, error: "Failed to save setting" },
      { status: 500 },
    );
  }
}

/**
 * DELETE /api/staff/settings
 * Delete a setting
 */
export async function DELETE(request: NextRequest) {
  try {
    // Validate staff session (super admin only for delete)
    const session = await validateStaffSession(request);
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    if (session.role !== "SUPER_ADMIN") {
      return NextResponse.json(
        { error: "Super admin access required for deletion" },
        { status: 403 },
      );
    }

    const body = await request.json();
    const validationResult = deleteSettingSchema.safeParse(body);

    if (!validationResult.success) {
      return NextResponse.json(
        {
          success: false,
          error: "Invalid request: " + validationResult.error.errors[0].message,
        },
        { status: 400 },
      );
    }

    const { key } = validationResult.data;

    const success = await systemSettingsService.delete(key);

    if (!success) {
      return NextResponse.json(
        {
          success: false,
          error: "Failed to delete setting or setting not found",
        },
        { status: 404 },
      );
    }

    logger.info("Setting deleted by staff", {
      key,
      staffId: session.staffId,
    });

    return NextResponse.json({
      success: true,
      message: `Setting "${key}" deleted successfully`,
    });
  } catch (error) {
    logger.error("Failed to delete setting", { error });
    return NextResponse.json(
      { success: false, error: "Failed to delete setting" },
      { status: 500 },
    );
  }
}
