import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import {
  requireApiAuthWithPermission,
  handleApiError,
} from "@/lib/api-auth";

type RouteContext = { params: Promise<{ id: string; fieldId: string }> };

async function getOwnedField(templateId: string, fieldId: string, orgId: string) {
  const template = await prisma.formTemplate.findUnique({
    where: { id: templateId },
    select: { organizationId: true },
  });
  if (!template || template.organizationId !== orgId) return null;

  const field = await prisma.formField.findUnique({
    where: { id: fieldId },
  });
  if (!field || field.formTemplateId !== templateId) return null;

  return field;
}

export async function PUT(request: NextRequest, ctx: RouteContext) {
  try {
    const session = await requireApiAuthWithPermission("settings.edit");
    const { id, fieldId } = await ctx.params;

    const field = await getOwnedField(id, fieldId, session.user.orgId!);
    if (!field) {
      return NextResponse.json(
        { error: "Field not found" },
        { status: 404 }
      );
    }

    const body = await request.json();
    const {
      label, type, section, required, removable, options,
      placeholder, helpText, validation, visibleOnCard, visibleOnSurvey,
    } = body as {
      label?: string;
      type?: string;
      section?: string;
      required?: boolean;
      removable?: boolean;
      options?: unknown;
      placeholder?: string;
      helpText?: string;
      validation?: unknown;
      visibleOnCard?: boolean;
      visibleOnSurvey?: boolean;
    };

    const data: Record<string, unknown> = {};
    if (label !== undefined) data.label = label.trim();
    if (type !== undefined) data.type = type.trim();
    if (section !== undefined) data.section = section.trim();
    if (required !== undefined) data.required = Boolean(required);
    if (removable !== undefined) data.removable = Boolean(removable);
    if (options !== undefined) data.options = options;
    if (placeholder !== undefined) data.placeholder = placeholder?.trim() || null;
    if (helpText !== undefined) data.helpText = helpText?.trim() || null;
    if (validation !== undefined) data.validation = validation;
    if (visibleOnCard !== undefined) data.visibleOnCard = Boolean(visibleOnCard);
    if (visibleOnSurvey !== undefined) data.visibleOnSurvey = Boolean(visibleOnSurvey);

    const updated = await prisma.formField.update({
      where: { id: fieldId },
      data,
    });

    return NextResponse.json(updated);
  } catch (error) {
    return handleApiError(error);
  }
}

export async function DELETE(_request: NextRequest, ctx: RouteContext) {
  try {
    const session = await requireApiAuthWithPermission("settings.edit");
    const { id, fieldId } = await ctx.params;

    const field = await getOwnedField(id, fieldId, session.user.orgId!);
    if (!field) {
      return NextResponse.json(
        { error: "Field not found" },
        { status: 404 }
      );
    }

    if (field.isCore) {
      return NextResponse.json(
        { error: "Core fields cannot be deleted" },
        { status: 403 }
      );
    }

    await prisma.formField.delete({ where: { id: fieldId } });
    return NextResponse.json({ deleted: true });
  } catch (error) {
    return handleApiError(error);
  }
}
