import "server-only";

import { Query } from "node-appwrite";

import { createAdminClient } from "./server";
import {
  DATABASE_ID,
  TABLES,
  type CustomerSoftware,
  type Software,
} from "./schema";

export async function listSoftware(tenantId: string): Promise<Software[]> {
  try {
    const { tablesDB } = createAdminClient();
    const result = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.software,
      queries: [
        Query.equal("tenantId", tenantId),
        Query.orderAsc("name"),
        Query.limit(500),
      ],
    });
    return result.rows as unknown as Software[];
  } catch {
    return [];
  }
}

export async function listAssignments(tenantId: string): Promise<CustomerSoftware[]> {
  try {
    const { tablesDB } = createAdminClient();
    const result = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.customerSoftware,
      queries: [
        Query.equal("tenantId", tenantId),
        Query.orderDesc("$createdAt"),
        Query.limit(1000),
      ],
    });
    return result.rows as unknown as CustomerSoftware[];
  } catch {
    return [];
  }
}
