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 { listOperationalBeds } from "@/modules/core/server/operations";
import { beds, rooms } from "@/modules/core/server/schema";
import type { BedStatus } from "@/modules/core/types";

const BED_STATUS_VALUES: BedStatus[] = ["available", "occupied", "maintenance", "disabled"];

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 readOptionalBedStatus(value: string): BedStatus | null | undefined {
  if (!value) {
    return undefined;
  }

  return BED_STATUS_VALUES.find((status) => status === value) ?? null;
}

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

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

  const bedsData = await listOperationalBeds(auth.context.organization?.id);
  return jsonSuccess("床位列表已加载", { beds: bedsData });
}

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

  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 roomId = readString(body, "roomId");
  const code = readString(body, "code");
  if (!roomId || !code) {
    return jsonFailure("房间和床位编号不能为空");
  }
  const status = readOptionalBedStatus(readString(body, "status"));
  if (status === null) {
    return jsonFailure("床位状态无效");
  }

  const database = getDatabase();
  const roomRows = await database
    .select()
    .from(rooms)
    .where(and(eq(rooms.id, roomId), eq(rooms.organizationId, organizationId)))
    .limit(1);
  const room = roomRows[0];
  if (!room) {
    return jsonFailure("房间不存在", 404);
  }

  const createdRows = await database
    .insert(beds)
    .values({
      organizationId,
      roomId,
      code,
      status: status ?? "available",
      notes: readString(body, "notes"),
    })
    .returning();
  const bed = createdRows[0];
  if (!bed) {
    return jsonFailure("床位创建失败", 500);
  }

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

  return jsonSuccess("床位已创建", { bed }, 201);
}
