/**
 * Cảnh báo nào người xem được thấy. Ban giám đốc thấy tất cả; quản lý chỉ thấy cảnh báo về khách hàng, nhân viên
 * và khu vực nằm trong phạm vi của mình. Cảnh báo sản phẩm là cấp công ty nên ai xem được mục Cảnh báo đều thấy.
 */
import { and, eq, inArray, or, sql, type SQL } from "drizzle-orm";
import { db } from "@/db";
import { alerts, customers } from "@/db/schema";
import type { SessionUser } from "./auth";
import { scopeFilter, visibleTerritoryIds, visibleUserIds } from "./rbac";

const NONE = ["00000000-0000-0000-0000-000000000000"];

export async function alertScope(session: SessionUser): Promise<SQL | undefined> {
  const tenant = eq(alerts.tenantId, session.tenantId);
  if (session.role === "DIRECTOR") return tenant;

  const [userIds, territoryIds, customerScope] = await Promise.all([
    visibleUserIds(session),
    visibleTerritoryIds(session),
    scopeFilter(session, {
      tenantId: customers.tenantId,
      ownerId: customers.ownerId,
      territoryId: customers.territoryId,
    }),
  ]);

  return and(
    tenant,
    or(
      eq(alerts.entityType, "product"),
      and(eq(alerts.entityType, "customer"), inArray(alerts.entityId, db.select({ id: customers.id }).from(customers).where(customerScope))),
      // null = chưa gán phòng ban (lùi về phạm vi cũ) — không giới hạn theo người.
      and(eq(alerts.entityType, "user"), userIds ? inArray(alerts.entityId, userIds.length > 0 ? userIds : NONE) : sql`true`),
      and(eq(alerts.entityType, "territory"), territoryIds ? inArray(alerts.entityId, territoryIds.length > 0 ? territoryIds : NONE) : sql`true`),
    ),
  );
}
