import { and, eq } from "drizzle-orm";

import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { getDatabase } from "@/modules/core/server/db";
import { listOperationalRooms } from "@/modules/core/server/operations";
import { floors, rooms } from "@/modules/core/server/schema";

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

function readString(source: Record<string, unknown>, key: string): string {
  const value = source[key];
  return typeof value === "string" ? value.trim() : "";
}

function readOptionalPositiveNumber(source: Record<string, unknown>, key: string): number | null | undefined {
  const value = source[key];
  if (value === undefined || value === null || value === "") {
    return undefined;
  }

  const numeric = typeof value === "number" ? value : Number(value);
  return Number.isInteger(numeric) && numeric > 0 ? numeric : null;
}

export async function GET(): Promise<Response> {
  const auth = await requirePermission("facility:read", {
    action: "room.list",
    targetType: "room",
  });

  if (!auth.success) {
    return auth.response;
  }

  const roomsData = await listOperationalRooms(auth.context.organization?.id);
  return jsonSuccess("房间列表已加载", { rooms: roomsData });
}

export async function POST(request: Request): Promise<Response> {
  const auth = await requirePermission("facility:manage", {
    action: "room.create",
    targetType: "room",
  });

  if (!auth.success) {
    return auth.response;
  }

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

  const body = await readJsonBody(request);
  if (!isRecord(body)) {
    return jsonFailure("请求数据格式无效");
  }

  const roomName = readString(body, "name");
  const roomCode = readString(body, "code");
  const floorId = readString(body, "floorId");
  if (!roomName || !roomCode || !floorId) {
    return jsonFailure("房间名称、编号和楼层不能为空");
  }
  const capacityInput = readOptionalPositiveNumber(body, "capacity");
  if (capacityInput === null) {
    return jsonFailure("房间容量需为正整数");
  }
  const capacity = capacityInput ?? 1;

  const database = getDatabase();
  const floorRows = await database
    .select({ id: floors.id })
    .from(floors)
    .where(and(eq(floors.id, floorId), eq(floors.organizationId, organizationId)))
    .limit(1);
  const floor = floorRows[0];
  if (!floor) {
    return jsonFailure("楼层不存在", 404);
  }

  const createdRows = await database
    .insert(rooms)
    .values({
      organizationId,
      floorId: floor.id,
      name: roomName,
      code: roomCode,
      capacity,
    })
    .returning();

  const room = createdRows[0];
  if (!room) {
    return jsonFailure("房间创建失败", 500);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "room.create",
    targetType: "room",
    targetId: room.id,
    result: "success",
    reason: `新增房间：${room.name}`,
  });

  return jsonSuccess("房间已创建", { room }, 201);
}
