import "server-only";

import { Permission, Role } from "node-appwrite";

import type { FinanceScope } from "./schema";

/**
 * Returns row-level permissions for finance-related entities.
 *
 * - `company`: visible to the whole tenant team. Owner/admin can delete.
 * - `personal`: visible/editable/deletable only by the creator.
 *
 * The Appwrite "users" table-level perms still gate writes; these row-level
 * perms gate reads and per-row mutations.
 */
export function scopedRowPermissions(
  tenantId: string,
  createdBy: string,
  scope: FinanceScope,
): string[] {
  if (scope === "personal") {
    return [
      Permission.read(Role.user(createdBy)),
      Permission.update(Role.user(createdBy)),
      Permission.delete(Role.user(createdBy)),
    ];
  }
  return [
    Permission.read(Role.team(tenantId)),
    Permission.update(Role.team(tenantId)),
    Permission.delete(Role.team(tenantId, "owner")),
    Permission.delete(Role.team(tenantId, "admin")),
  ];
}

export function normalizeScope(v: unknown): FinanceScope {
  return v === "personal" ? "personal" : "company";
}

/**
 * Returns true if the current user is allowed to read the row.
 * - company-scope: any team member
 * - personal-scope: only the creator
 */
export function canAccessRow(
  row: { scope?: FinanceScope; createdBy?: string },
  currentUserId: string,
): boolean {
  if ((row.scope ?? "company") === "personal") {
    return row.createdBy === currentUserId;
  }
  return true;
}
