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";
import { validateElderInput } from "@/modules/elders/types";

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

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

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

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后更新老人档案", 400);
  }

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

  const database = getDatabase();
  const updated = await database
    .update(elders)
    .set({
      name: input.data.name,
      gender: input.data.gender,
      age: input.data.age,
      careLevel: input.data.careLevel,
      status: input.data.status,
      primaryContact: input.data.primaryContact,
      phone: input.data.phone,
      medicalNotes: input.data.medicalNotes,
      updatedAt: new Date(),
    })
    .where(and(eq(elders.id, id), eq(elders.organizationId, organizationId)))
    .returning();
  const elder = updated[0];

  if (!elder) {
    return jsonFailure("老人档案不存在", 404);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "elder.update",
    targetType: "elder",
    targetId: elder.id,
    result: "success",
    reason: `更新老人档案：${elder.name}`,
  });

  return jsonSuccess("老人档案已更新", {
    elder: {
      id: elder.id,
      organizationId: elder.organizationId,
      name: elder.name,
      gender: elder.gender,
      age: elder.age,
      careLevel: elder.careLevel,
      room: "",
      bed: "",
      status: elder.status,
      primaryContact: elder.primaryContact,
      phone: elder.phone,
      medicalNotes: elder.medicalNotes,
      createdAt: elder.createdAt.toISOString(),
      updatedAt: elder.updatedAt.toISOString(),
    },
  });
}

export async function DELETE(_request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("elder:delete", {
    action: "elder.delete",
    targetType: "elder",
    targetId: id,
  });

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

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后删除老人档案", 400);
  }

  const database = getDatabase();
  const deleted = await database.transaction(async (transaction) => {
    const elderRows = await transaction
      .select()
      .from(elders)
      .where(and(eq(elders.id, id), eq(elders.organizationId, organizationId)))
      .limit(1);
    const elder = elderRows[0];
    if (!elder) {
      return null;
    }

    const activeAdmissions = await transaction
      .select()
      .from(admissions)
      .where(and(eq(admissions.elderId, id), eq(admissions.organizationId, organizationId), eq(admissions.status, "active")));

    await Promise.all(
      activeAdmissions.map((admission) =>
        transaction
        .update(admissions)
        .set({ status: "discharged", dischargedAt: new Date(), updatedAt: new Date() })
          .where(eq(admissions.id, admission.id)),
      ),
    );
    await Promise.all(
      activeAdmissions.map((admission) =>
        transaction
          .update(beds)
          .set({ status: "available", updatedAt: new Date() })
          .where(and(eq(beds.id, admission.bedId), eq(beds.organizationId, organizationId))),
      ),
    );

    await transaction.delete(elders).where(eq(elders.id, id));
    return elder;
  });

  if (!deleted) {
    return jsonFailure("老人档案不存在", 404);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "elder.delete",
    targetType: "elder",
    targetId: deleted.id,
    result: "success",
    reason: `删除老人档案：${deleted.name}`,
  });

  return jsonSuccess("老人档案已删除", { elder: { id: deleted.id, name: deleted.name } });
}
