import { NextResponse } from "next/server";
import { Query } from "node-appwrite";

import { calculateJobPriceForProsthetic } from "@/lib/appwrite/pricing";
import {
  DATABASE_ID,
  TABLES,
  type Connection,
  type Prosthetic,
} from "@/lib/appwrite/schema";
import { createAdminClient } from "@/lib/appwrite/server";
import { requireTenant, requireTenantKind } from "@/lib/appwrite/tenant-guard";

export async function POST(request: Request) {
  let ctx;
  try {
    ctx = await requireTenant();
    requireTenantKind(ctx, ["clinic"]);
  } catch {
    return NextResponse.json({ ok: false, error: "Yetki yok." }, { status: 401 });
  }

  let body: { prostheticId?: string; teethCount?: number };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ ok: false, error: "Geçersiz istek." }, { status: 400 });
  }

  const prostheticId = String(body.prostheticId ?? "").trim();
  const teethCount = Number(body.teethCount);
  if (!prostheticId || !Number.isFinite(teethCount) || teethCount <= 0) {
    return NextResponse.json({ ok: true, quote: null });
  }

  const { tablesDB } = createAdminClient();

  let prosthetic: Prosthetic;
  try {
    const row = await tablesDB.getRow(DATABASE_ID, TABLES.prosthetics, prostheticId);
    prosthetic = row as unknown as Prosthetic;
  } catch {
    return NextResponse.json({ ok: true, quote: null });
  }
  if (prosthetic.archived) {
    return NextResponse.json({ ok: true, quote: null });
  }

  // Only return a quote if the clinic actually has an approved bond with the
  // lab that owns this product — keeps catalog data private to connected pairs.
  const connRes = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.connections,
    queries: [
      Query.equal("clinicTenantId", ctx.tenantId),
      Query.equal("labTenantId", prosthetic.tenantId),
      Query.equal("status", "approved"),
      Query.limit(1),
    ],
  });
  if (!(connRes.rows[0] as unknown as Connection | undefined)) {
    return NextResponse.json({ ok: true, quote: null });
  }

  const quote = await calculateJobPriceForProsthetic({
    prosthetic,
    clinicTenantId: ctx.tenantId,
    teethCount,
  });
  return NextResponse.json({ ok: true, quote });
}
