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 { admissions, beds, elders } from "@/modules/core/server/schema";

type RouteContext = {
  params: Promise<{
    id: string;
  }>;
};

type AdmissionRow = typeof admissions.$inferSelect;

type DischargeResult =
  | {
      success: true;
      admission: AdmissionRow;
    }
  | {
      success: false;
      reason: string;
      status: number;
    };

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() : "";
}

export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("admission:manage", {
    action: "admission.discharge",
    targetType: "admission",
    targetId: id,
  });

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

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后办理退住", 400);
  }

  const body = await readJsonBody(request);
  const notes = isRecord(body) ? readString(body, "notes") : "";

  const database = getDatabase();
  const result = await database.transaction(async (transaction): Promise<DischargeResult> => {
    const admissionRows = await transaction
      .select()
      .from(admissions)
      .where(and(eq(admissions.id, id), eq(admissions.organizationId, organizationId)))
      .limit(1);
    const admission = admissionRows[0];
    if (!admission) {
      return { success: false, reason: "入住记录不存在", status: 404 };
    }

    if (admission.status !== "active") {
      return { success: false, reason: "该入住记录已结束", status: 409 };
    }

    const updatedRows = await transaction
      .update(admissions)
      .set({
        status: "discharged",
        dischargedAt: new Date(),
        notes: notes || admission.notes,
        updatedAt: new Date(),
      })
      .where(eq(admissions.id, admission.id))
      .returning();
    const updated = updatedRows[0];
    if (!updated) {
      return { success: false, reason: "退住记录更新失败", status: 500 };
    }

    await transaction.update(beds).set({ status: "available", updatedAt: new Date() }).where(eq(beds.id, admission.bedId));
    await transaction.update(elders).set({ status: "discharged", updatedAt: new Date() }).where(eq(elders.id, admission.elderId));

    return { success: true, admission: updated };
  });

  if (!result.success) {
    return jsonFailure(result.reason, result.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "admission.discharge",
    targetType: "admission",
    targetId: result.admission.id,
    result: "success",
    reason: "办理退住",
  });

  return jsonSuccess("退住已办理", { admission: result.admission });
}
