import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { createFamilyContact, isFamilyMutationFailure, listFamilyServiceData } from "@/modules/family/server/operations";
import { validateFamilyContactInput } from "@/modules/family/types";

export async function GET(): Promise<Response> {
  const auth = await requirePermission("family:read", { action: "family.contact.list", targetType: "family_contact" });
  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后查看家属服务", 400);
  }

  const data = await listFamilyServiceData(organizationId);
  return jsonSuccess("家属服务已加载", { data });
}

export async function POST(request: Request): Promise<Response> {
  const auth = await requirePermission("family:manage", { action: "family.contact.create", targetType: "family_contact" });
  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后维护家属联系人", 400);
  }

  const input = validateFamilyContactInput(await readJsonBody(request));
  if (!input.success) {
    return jsonFailure(input.reason);
  }

  const contact = await createFamilyContact({ ...input.data, organizationId });
  if (isFamilyMutationFailure(contact)) {
    return jsonFailure(contact.reason, contact.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "family.contact.create",
    targetType: "family_contact",
    targetId: contact.id,
    result: "success",
    reason: `创建家属联系人：${contact.name}`,
  });

  return jsonSuccess("家属联系人已创建", { contact }, 201);
}
