/**
 * Staff Organizations API
 *
 * GET  /api/staff/organizations - List all organizations (id, name, ownerId, twilioWhatsappNumber masked, industry)
 * PATCH /api/staff/organizations - Update an org's Twilio credentials
 *
 * Only accessible to ADMIN and SUPER_ADMIN staff.
 */

import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import { prisma } from "@/lib/db";
import { z } from "zod";

const patchSchema = z.object({
  id: z.string().min(1),
  twilioAccountSid: z.string().optional(),
  twilioAuthToken: z.string().optional(),
  twilioWhatsappNumber: z.string().optional(),
});

export async function GET(request: NextRequest) {
  try {
    const staffUser = await validateStaffSession(request);
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const orgs = await prisma.organizations.findMany({
      select: {
        id: true,
        name: true,
        ownerId: true,
        industry: true,
        twilioWhatsappNumber: true,
        twilioAccountSid: true,
      },
      orderBy: { createdAt: "desc" },
    } as Parameters<typeof prisma.organizations.findMany>[0]);

    // Mask Twilio Account SID: show first 8 + asterisks
    const masked = (orgs as Array<Record<string, unknown>>).map((org) => ({
      id: org.id,
      name: org.name,
      ownerId: org.ownerId,
      industry: org.industry ?? null,
      twilioWhatsappNumber: org.twilioWhatsappNumber ?? null,
      twilioAccountSidMasked:
        typeof org.twilioAccountSid === "string" && org.twilioAccountSid
          ? org.twilioAccountSid.slice(0, 8) + "••••••••••••••"
          : null,
      hasCredentials:
        typeof org.twilioAccountSid === "string" && !!org.twilioAccountSid,
    }));

    return NextResponse.json({ organizations: masked });
  } catch (error) {
    console.error("GET /api/staff/organizations error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const staffUser = await validateStaffSession(request);
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Only ADMIN and SUPER_ADMIN can edit credentials
    if (!["ADMIN", "SUPER_ADMIN"].includes(staffUser.role)) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const body = await request.json();
    const parsed = patchSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        { error: "Invalid request", details: parsed.error.flatten() },
        { status: 400 },
      );
    }

    const { id, twilioAccountSid, twilioAuthToken, twilioWhatsappNumber } =
      parsed.data;

    const updateData: Record<string, unknown> = {};
    if (twilioAccountSid !== undefined)
      updateData.twilioAccountSid = twilioAccountSid;
    if (twilioAuthToken !== undefined)
      updateData.twilioAuthToken = twilioAuthToken;
    if (twilioWhatsappNumber !== undefined)
      updateData.twilioWhatsappNumber = twilioWhatsappNumber;

    if (Object.keys(updateData).length === 0) {
      return NextResponse.json(
        { error: "No fields to update" },
        { status: 400 },
      );
    }

    await prisma.organizations.update({
      where: { id },
      data: updateData,
    } as Parameters<typeof prisma.organizations.update>[0]);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("PATCH /api/staff/organizations error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
