import "server-only";

import { Query } from "node-appwrite";

import { createAdminClient } from "./server";
import { DATABASE_ID, TABLES, type Lead, type LeadActivity } from "./schema";

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

export async function getLead(tenantId: string, leadId: string): Promise<Lead | null> {
  try {
    const { tablesDB } = createAdminClient();
    const row = await tablesDB.getRow(DATABASE_ID, TABLES.leads, leadId);
    const lead = row as unknown as Lead;
    if (lead.tenantId !== tenantId) return null;
    return lead;
  } catch {
    return null;
  }
}

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