import { createFileRoute } from "@tanstack/react-router";
import { supabaseAdmin } from "@/integrations/supabase/client.server";
import { dispatchSms } from "@/lib/sms-providers.server";

const BD_PHONE = /^01[3-9]\d{8}$/;

function normalizePhone(raw: string): string | null {
  const digits = (raw || "").replace(/\D/g, "");
  if (digits.startsWith("880") && digits.length === 13) return "0" + digits.slice(3);
  if (digits.length === 11) return digits;
  if (digits.length === 10 && digits.startsWith("1")) return "0" + digits;
  return null;
}

async function runFlush() {
  const { data: settings } = await supabaseAdmin
    .from("sms_settings")
    .select("*")
    .limit(1)
    .maybeSingle();

  if (!settings || !settings.sms_enabled || !settings.api_token || !settings.sender_id) {
    return { processed: 0, sent: 0, failed: 0, skipped: true };
  }

  const { data: pending } = await supabaseAdmin
    .from("sms_logs")
    .select("*")
    .eq("status", "pending")
    .order("created_at", { ascending: true })
    .limit(100);

  let sent = 0;
  let failed = 0;
  for (const row of pending ?? []) {
    const phone = normalizePhone(row.phone);
    if (!phone || !BD_PHONE.test(phone)) {
      await supabaseAdmin
        .from("sms_logs")
        .update({ status: "failed", error_message: "Invalid phone format" })
        .eq("id", row.id);
      failed++;
      continue;
    }
    try {
      const result = await dispatchSms({
        provider: settings.provider,
        baseUrl: settings.base_url,
        apiToken: settings.api_token,
        username: settings.api_secret,
        sid: settings.sender_id,
        phone,
        message: row.message,
        csms_id: row.id,
      });
      const ok = result.ok;
      await supabaseAdmin
        .from("sms_logs")
        .update({
          status: ok ? "sent" : "failed",
          provider_response: (result.body ?? {}) as never,
          error_message: ok ? "" : result.errorMessage || `HTTP ${result.status}`,
          sent_at: ok ? new Date().toISOString() : null,
        })
        .eq("id", row.id);
      ok ? sent++ : failed++;
    } catch (e) {
      const msg = e instanceof Error ? e.message : String(e);
      await supabaseAdmin
        .from("sms_logs")
        .update({ status: "failed", error_message: msg })
        .eq("id", row.id);
      failed++;
    }
  }
  return { processed: pending?.length ?? 0, sent, failed, skipped: false };
}

export const Route = createFileRoute("/api/public/hooks/sms-flush")({
  server: {
    handlers: {
      POST: async () => {
        try {
          const result = await runFlush();
          return new Response(JSON.stringify({ ok: true, ...result }), {
            headers: { "Content-Type": "application/json" },
          });
        } catch (e) {
          const msg = e instanceof Error ? e.message : String(e);
          return new Response(JSON.stringify({ ok: false, error: msg }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
      GET: async () => {
        const result = await runFlush();
        return new Response(JSON.stringify({ ok: true, ...result }), {
          headers: { "Content-Type": "application/json" },
        });
      },
    },
  },
});
