import "server-only";

import { Query } from "node-appwrite";

import { createAdminClient } from "./appwrite/server";
import { DATABASE_ID, TABLES, type TenantPlan } from "./appwrite/schema";
import { PLAN_NAMES } from "./appwrite/plan-limits-shared";

const INF = Number.POSITIVE_INFINITY;

export const PLAN_LIMITS = {
  free:       { properties: 15,  customers: 25,  presentations: 5,   teamMembers: 1,   propertyImages: 5  },
  starter:    { properties: 50,  customers: 100, presentations: 20,  teamMembers: 3,   propertyImages: 10 },
  pro:        { properties: 200, customers: 500, presentations: 50,  teamMembers: 10,  propertyImages: 20 },
  enterprise: { properties: INF, customers: INF, presentations: INF, teamMembers: INF, propertyImages: INF },
} as const;

export type LimitKey = keyof typeof PLAN_LIMITS.free;

export type LimitResult = { allowed: boolean; current: number; limit: number };

export async function checkLimit(
  tenantId: string,
  plan: TenantPlan | undefined | null,
  key: LimitKey,
): Promise<LimitResult> {
  const planKey: TenantPlan = plan ?? "free";
  const limit = PLAN_LIMITS[planKey][key];

  if (limit === INF) return { allowed: true, current: 0, limit: INF };

  const { tablesDB, teams } = createAdminClient();
  let current = 0;

  if (key === "properties") {
    // Satılan/kiralanan ilanlar limite dahil değil.
    // Query.or() bypasses compound indexes; 3 parallel count queries each use [tenantId, status].
    const [aktifRes, rezerveRes, pasifRes] = await Promise.all([
      tablesDB.listRows({ databaseId: DATABASE_ID, tableId: TABLES.properties, queries: [Query.equal("tenantId", tenantId), Query.equal("status", "aktif"), Query.limit(1)] }),
      tablesDB.listRows({ databaseId: DATABASE_ID, tableId: TABLES.properties, queries: [Query.equal("tenantId", tenantId), Query.equal("status", "rezerve"), Query.limit(1)] }),
      tablesDB.listRows({ databaseId: DATABASE_ID, tableId: TABLES.properties, queries: [Query.equal("tenantId", tenantId), Query.equal("status", "pasif"), Query.limit(1)] }),
    ]);
    current = aktifRes.total + rezerveRes.total + pasifRes.total;
  } else if (key === "customers") {
    const r = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.customers,
      queries: [Query.equal("tenantId", tenantId), Query.limit(1)],
    });
    current = r.total;
  } else if (key === "presentations") {
    const r = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.presentations,
      queries: [Query.equal("tenantId", tenantId), Query.limit(1)],
    });
    current = r.total;
  } else if (key === "teamMembers") {
    const r = await teams.listMemberships(tenantId);
    current = r.memberships.filter((m) => m.confirm).length;
  }

  return { allowed: current < limit, current, limit };
}

export function limitLabel(key: LimitKey): string {
  const labels: Record<LimitKey, string> = {
    properties:    "aktif ilan",
    customers:     "müşteri",
    presentations: "sunum",
    teamMembers:   "ekip üyesi",
    propertyImages: "fotoğraf",
  };
  return labels[key];
}

export function limitErrorMessage(
  key: LimitKey,
  limit: number,
  role: "owner" | "admin" | "member",
  plan?: TenantPlan | null,
): string {
  if (role === "owner") {
    const planName = plan ? (PLAN_NAMES[plan] ?? "Mevcut") : "Mevcut";
    return `${planName} planda en fazla ${limit} ${limitLabel(key)} ekleyebilirsiniz. Planınızı yükselterek devam edin.`;
  }
  return `Bu çalışma alanı ${limitLabel(key)} limitine ulaştı. Yöneticinizle iletişime geçin.`;
}
