import "server-only";

import { Query } from "node-appwrite";

import { createAdminClient } from "./server";
import { DATABASE_ID, TABLES, type Invoice, type InvoiceItem } from "./schema";

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

export async function getInvoice(
  tenantId: string,
  id: string,
): Promise<Invoice | null> {
  try {
    const { tablesDB } = createAdminClient();
    const row = (await tablesDB.getRow(
      DATABASE_ID,
      TABLES.invoices,
      id,
    )) as unknown as Invoice;
    if (row.tenantId !== tenantId) return null;
    return row;
  } catch {
    return null;
  }
}

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