import { randomBytes } from "node:crypto";

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 { organizationInvitations, organizations, roles } from "@/modules/core/server/schema";

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

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 createInvitationToken(): string {
  return randomBytes(24).toString("base64url");
}

export async function POST(request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("account:manage", {
    action: "organizationInvitation.create",
    targetType: "organization",
    targetId: id,
  });

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

  const activeOrganizationId = auth.context.organization?.id;
  if (activeOrganizationId && activeOrganizationId !== id) {
    return jsonFailure("不能为其他机构创建邀请", 403);
  }

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

  const email = readString(body, "email");
  const roleId = readString(body, "roleId");
  if (!roleId) {
    return jsonFailure("请选择邀请角色");
  }

  const database = getDatabase();
  const organizationRows = await database.select().from(organizations).where(eq(organizations.id, id)).limit(1);
  const organization = organizationRows[0];
  if (!organization) {
    return jsonFailure("机构不存在", 404);
  }

  const roleRows = await database
    .select()
    .from(roles)
    .where(and(eq(roles.id, roleId), eq(roles.organizationId, id), eq(roles.isEnabled, true)))
    .limit(1);
  const role = roleRows[0];
  if (!role) {
    return jsonFailure("角色不存在", 404);
  }

  const rows = await database
    .insert(organizationInvitations)
    .values({
      organizationId: id,
      roleId: role.id,
      email,
      token: createInvitationToken(),
      status: "active",
      createdByAccountId: auth.context.account.id,
      expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
    })
    .returning();
  const invitation = rows[0];
  if (!invitation) {
    return jsonFailure("邀请创建失败", 500);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId: id,
    action: "organizationInvitation.create",
    targetType: "organizationInvitation",
    targetId: invitation.id,
    result: "success",
    reason: `创建机构邀请：${email || "通用邀请"}`,
  });

  return jsonSuccess("邀请已创建", { invitation }, 201);
}
