import "server-only";

import { Query } from "node-appwrite";

import {
  DATABASE_ID,
  TABLES,
  type ClinicPricing,
  type Prosthetic,
  type ProstheticType,
  type TenantSettings,
} from "./schema";
import { createAdminClient } from "./server";

export type JobPriceQuote = {
  amount: number;
  currency: string;
  source: "clinic_custom" | "clinic_discount" | "catalog";
  unitPrice: number;
  discountPercent?: number;
};

/**
 * Resolves the price a clinic should be charged for a job, given the lab's
 * catalog and any clinic-specific pricing overrides.
 *
 * Cascade (first match wins):
 *   1. clinic_pricing row for (lab, clinic, type) with customUnitPrice → use it
 *   2. clinic_pricing row with discountPercent → catalog unitPrice × (1 - d/100)
 *   3. lab's prosthetics catalog row matching `type` (not archived)
 *   4. nothing → returns null, the lab will need to set the price manually
 *
 * Currency precedence: clinic override → catalog → lab tenant default → "TRY".
 *
 * @param teethCount  multiplied with the resolved unit price
 */
export async function calculateJobPrice(opts: {
  labTenantId: string;
  clinicTenantId: string;
  prostheticType: ProstheticType;
  teethCount: number;
}): Promise<JobPriceQuote | null> {
  if (opts.teethCount <= 0) return null;
  const { tablesDB } = createAdminClient();

  const [pricingRes, catalogRes, labSettingsRes] = await Promise.all([
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.clinicPricing,
      queries: [
        Query.equal("labTenantId", opts.labTenantId),
        Query.equal("clinicTenantId", opts.clinicTenantId),
        Query.equal("prostheticType", opts.prostheticType),
        Query.limit(1),
      ],
    }),
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.prosthetics,
      queries: [
        Query.equal("tenantId", opts.labTenantId),
        Query.equal("type", opts.prostheticType),
        Query.notEqual("archived", true),
        Query.orderAsc("$createdAt"),
        Query.limit(1),
      ],
    }),
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.tenantSettings,
      queries: [Query.equal("tenantId", opts.labTenantId), Query.limit(1)],
    }),
  ]);

  const override = pricingRes.rows[0] as unknown as ClinicPricing | undefined;
  const catalog = catalogRes.rows[0] as unknown as Prosthetic | undefined;
  const labSettings = labSettingsRes.rows[0] as unknown as TenantSettings | undefined;

  const fallbackCurrency = labSettings?.defaultCurrency ?? "TRY";

  if (override?.customUnitPrice !== undefined && override.customUnitPrice !== null) {
    const unit = override.customUnitPrice;
    return {
      amount: unit * opts.teethCount,
      currency: override.currency || catalog?.currency || fallbackCurrency,
      source: "clinic_custom",
      unitPrice: unit,
    };
  }

  if (!catalog) return null;

  if (
    override?.discountPercent !== undefined &&
    override.discountPercent !== null &&
    override.discountPercent > 0
  ) {
    const discounted = catalog.unitPrice * (1 - override.discountPercent / 100);
    return {
      amount: discounted * opts.teethCount,
      currency: override.currency || catalog.currency || fallbackCurrency,
      source: "clinic_discount",
      unitPrice: discounted,
      discountPercent: override.discountPercent,
    };
  }

  return {
    amount: catalog.unitPrice * opts.teethCount,
    currency: catalog.currency || fallbackCurrency,
    source: "catalog",
    unitPrice: catalog.unitPrice,
  };
}
