import { createFileRoute } from "@tanstack/react-router";
import { supabaseExtAdmin } from "@/integrations/external-supabase/client.server";
import { orderSubmitSchema } from "@/lib/orders.public";

export const Route = createFileRoute("/api/public/orders")({
  server: {
    handlers: {
      POST: async ({ request }) => {
        try {
          const body = await request.json();
          const input = orderSubmitSchema.parse(body);

          const { data: pkg, error: pkgErr } = await supabaseExtAdmin
            .from("packages")
            .select("id, name, credits, price_bdt, is_active")
            .eq("id", input.packageId)
            .maybeSingle();

          if (pkgErr || !pkg || !pkg.is_active) {
            return Response.json({ error: "Package not found" }, { status: 404 });
          }

          const totalCredits = pkg.credits * input.quantity;
          const totalBdt = pkg.price_bdt * input.quantity;

          const { data: order, error } = await supabaseExtAdmin
            .from("orders")
            .insert({
              package_id: pkg.id,
              package_name: pkg.name,
              credits_per_unit: pkg.credits,
              quantity: input.quantity,
              total_credits: totalCredits,
              total_bdt: totalBdt,
              customer_email: input.customerEmail,
              whatsapp: input.whatsapp || null,
              payment_method: input.paymentMethod,
              transaction_id: input.transactionId || null,
              notes: input.notes || null,
            })
            .select("id, order_number")
            .single();

          if (error) {
            console.error("Order insert error:", error);
            return Response.json({ error: "Could not save order" }, { status: 500 });
          }

          // Fire telegram notification (best-effort, non-blocking failure)
          try {
            const { notifyNewOrder } = await import("@/lib/telegram.server");
            await notifyNewOrder(order.id);
          } catch (e) {
            console.error("Telegram notify failed:", e);
          }

          return Response.json({ orderId: order.id, orderNumber: order.order_number });
        } catch (e: any) {
          if (e?.issues) {
            return Response.json({ error: "Invalid input", details: e.issues }, { status: 400 });
          }
          console.error(e);
          return Response.json({ error: "Server error" }, { status: 500 });
        }
      },
    },
  },
});