import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { switchActiveOrganization } from "@/modules/core/server/auth";

export const dynamic = "force-dynamic";

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

export async function POST(request: Request): Promise<Response> {
  const body = await readJsonBody(request);
  if (!isRecord(body) || typeof body.organizationId !== "string" || !body.organizationId.trim()) {
    return jsonFailure("机构不能为空");
  }

  try {
    const context = await switchActiveOrganization(body.organizationId.trim());

    return jsonSuccess("机构已切换", {
      account: context.account,
      organization: context.organization ?? null,
      organizations: context.organizations,
      membership: context.membership ?? null,
      permissions: context.permissions,
    });
  } catch (error) {
    return jsonFailure(error instanceof Error ? error.message : "机构切换失败", 403);
  }
}
