import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { createNotice, isNoticeMutationFailure, listNoticeCenterData } from "@/modules/notices/server/operations";
import { validateNoticeInput } from "@/modules/notices/types";

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

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

  const data = await listNoticeCenterData(organizationId, auth.context.account.id);
  return jsonSuccess("公告通知已加载", { data });
}

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

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

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

  const notice = await createNotice({ ...input.data, organizationId, accountId: auth.context.account.id });
  if (isNoticeMutationFailure(notice)) {
    return jsonFailure(notice.reason, notice.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "notice.create",
    targetType: "notice",
    targetId: notice.id,
    result: "success",
    reason: `创建公告：${notice.title}`,
  });

  return jsonSuccess("公告已创建", { notice }, 201);
}
