import { jsonSuccess } from "@/modules/core/server/api";
import { jsonFailure, 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 { getRoleDefinitions } from "@/modules/core/server/permissions";
import { rolePermissions, roles } from "@/modules/core/server/schema";
import type { Permission } from "@/modules/core/types";

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 readPermissionArray(source: Record<string, unknown>): Permission[] {
  const value = source.permissions;
  if (!Array.isArray(value)) {
    return [];
  }

  return value.filter((item): item is Permission => typeof item === "string");
}

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

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

  const roles = await getRoleDefinitions(auth.context.organization?.id);
  return jsonSuccess("角色列表已加载", { roles });
}

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

  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 label = readString(body, "label");
  const key = readString(body, "key") || label.toLowerCase().replace(/[^a-z0-9]+/g, "_");
  const description = readString(body, "description");
  const permissions = readPermissionArray(body);

  if (!label || !key) {
    return jsonFailure("角色名称不能为空");
  }

  const database = getDatabase();
  const created = await database.transaction(async (transaction) => {
    const rows = await transaction
      .insert(roles)
      .values({
        key,
        organizationId,
        scope: "organization",
        label,
        description: description || "机构自定义角色",
        isSystem: false,
        isEnabled: true,
      })
      .returning();
    const role = rows[0];
    if (!role) {
      throw new Error("角色创建失败");
    }

    if (permissions.length > 0) {
      await transaction.insert(rolePermissions).values(
        permissions.map((permissionId) => ({
          roleId: role.id,
          permissionId,
        })),
      );
    }

    return role;
  });

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "role.create",
    targetType: "role",
    targetId: created.id,
    result: "success",
    reason: `创建自定义角色：${created.label}`,
  });

  const roleRows = await getRoleDefinitions(organizationId);
  const role = roleRows.find((item) => item.id === created.id);
  if (!role) {
    return jsonFailure("角色创建后读取失败", 500);
  }

  return jsonSuccess("角色已创建", { role }, 201);
}
