// routes/index.js
// ==============================
// Route Initialization - WITH BROADCAST ROUTES
// ==============================

import { Router } from "express";
import { initializeClient, getClientStatus, terminateClient, checkConnection, getContacts, getPairingCode } from "../controllers/clientController.js";
import { sendMessage, sendMediaOnly, sendMediaMessage, sendLocation, sendProductCatalog, sendReaction, pinMessage, starMessage, sendContact, deleteMessage, editMessage } from "../controllers/messageController.js";
import { scheduleMessage, getScheduledMessages, scheduleBulkMessage, scheduleRecurring, sendBulkImmediate, pauseSchedule, resumeSchedule, cancelSchedule, updateSchedule } from "../controllers/scheduleController.js";
import { resumeByPhone, resumeForm, resumeGoogleFormEndpoint, resumePort, startFlow } from "../controllers/flowController.js";
import { answer as wabaCallAnswer, terminate as wabaCallTerminate } from "../controllers/wabaCallController.js";
import { sendBroadcastImmediate, scheduleBroadcast, pauseBroadcast, resumeBroadcast, cancelBroadcast, getBroadcasts, getBroadcastStatus } from "../controllers/broadcastController.js";
import {
  sendCampaignImmediate,
  scheduleCampaign,
  getCampaignDetails,
  pauseCampaign,
  resumeCampaign,
  cancelCampaign
} from '../controllers/campaignController.js';
import { flushSettingsCache } from "../utils/helpers.js";

export function initializeRoutes(app) {
  // Cache invalidation — Laravel POSTs here when WABA config, branding
  // footer, or platform footer changes so Node picks up the new value
  // immediately (instead of waiting up to 5min for the TTL). X-Node-Token
  // authed. Body: { phone?: '<digits>' }; omit phone to flush everything.
  app.post("/api/cache-bust", (req, res) => {
    const expected = process.env.NODE_WEBHOOK_TOKEN || "";
    const token    = req.headers["x-node-token"] || "";
    if (!expected || token !== expected) {
      return res.status(401).json({ ok: false, error: "unauthorized" });
    }
    const phone = String(req.body?.phone || "").replace(/\D+/g, "") || null;
    const n = flushSettingsCache(phone);
    return res.json({ ok: true, flushed: n, phone: phone || "(all)" });
  });

  // Client routes
  app.get("/api/initialize-client/:phoneNumber", (req, res) => initializeClient(req, res, app));
  app.get("/api/client-status/:phoneNumber", (req, res) => getClientStatus(req, res, app));
  app.get("/api/terminate-client/:phoneNumber", (req, res) => terminateClient(req, res, app));
  app.get("/api/check-connection/:phoneNumber", (req, res) => checkConnection(req, res, app));
  app.get("/api/get-contacts/:phoneNumber", (req, res) => getContacts(req, res, app));
  app.get("/api/get-pairing-code/:phoneNumber", (req, res) => getPairingCode(req, res, app));


  // Message routes
  app.post("/api/send-message/:phoneNumber", (req, res) => sendMessage(req, res, app));
  app.post("/api/send-media-only/:phoneNumber", (req, res) => sendMediaOnly(req, res, app));
  app.post("/api/send-media-message/:phoneNumber", (req, res) => sendMediaMessage(req, res, app));
  app.post("/api/send-location/:phoneNumber", (req, res) => sendLocation(req, res, app));
  app.post("/api/send-product-catalog/:phoneNumber", (req, res) => sendProductCatalog(req, res, app));
  app.post("/api/send-reaction/:phoneNumber", (req, res) => sendReaction(req, res, app));
  app.post("/api/pin-message/:phoneNumber",   (req, res) => pinMessage(req, res, app));
  app.post("/api/star-message/:phoneNumber",  (req, res) => starMessage(req, res, app));
  app.post("/api/send-contact/:phoneNumber",  (req, res) => sendContact(req, res, app));
  app.post("/api/delete-message/:phoneNumber",(req, res) => deleteMessage(req, res, app));
  app.post("/api/edit-message/:phoneNumber",  (req, res) => editMessage(req, res, app));

  // Schedule routes
  app.post("/api/schedule-message/:phoneNumber", (req, res) => scheduleMessage(req, res, app));
  app.get("/api/scheduled-messages/:phoneNumber", (req, res) => getScheduledMessages(req, res, app));
  app.post("/api/schedule-message-bulk/:phoneNumber", (req, res) => scheduleBulkMessage(req, res, app));
  app.post("/api/schedule-recurring/:phoneNumber", (req, res) => scheduleRecurring(req, res, app));
  app.post("/api/send-bulk-immediate/:phoneNumber", (req, res) => sendBulkImmediate(req, res, app));
  app.post("/api/pause-schedule/:scheduleId", (req, res) => pauseSchedule(req, res, app));
  app.post("/api/resume-schedule/:scheduleId", (req, res) => resumeSchedule(req, res, app));
  app.delete("/api/cancel-scheduled-message/:scheduleId", (req, res) => cancelSchedule(req, res, app));
  app.put("/api/update-schedule/:scheduleId", (req, res) => updateSchedule(req, res, app));

  // Broadcast routes (NEW)
  app.post("/api/broadcast/send-immediate/:phoneNumber", (req, res) => sendBroadcastImmediate(req, res, app));
  app.post("/api/broadcast/schedule/:phoneNumber", (req, res) => scheduleBroadcast(req, res, app));
  app.post("/api/broadcast/pause/:scheduleId", (req, res) => pauseBroadcast(req, res, app));
  app.post("/api/broadcast/resume/:scheduleId", (req, res) => resumeBroadcast(req, res, app));
  app.delete("/api/broadcast/cancel/:scheduleId", (req, res) => cancelBroadcast(req, res, app));
  app.get("/api/broadcast/list/:phoneNumber", (req, res) => getBroadcasts(req, res, app));
  app.get("/api/broadcast/status/:scheduleId", (req, res) => getBroadcastStatus(req, res, app));



  // Campaign routes
app.post('/api/wa/:phoneNumber/campaign/send', (req, res) => 
  sendCampaignImmediate(req, res, app)
);

app.post('/api/wa/:phoneNumber/campaign/schedule', (req, res) => 
  scheduleCampaign(req, res, app)
);

app.get('/api/wa/campaign/:campaignId/details', (req, res) => 
  getCampaignDetails(req, res, app)
);

app.post('/api/wa/campaign/:scheduleId/pause', (req, res) => 
  pauseCampaign(req, res, app)
);

app.post('/api/wa/campaign/:scheduleId/resume', (req, res) => 
  resumeCampaign(req, res, app)
);

app.post('/api/wa/campaign/:scheduleId/cancel', (req, res) => 
  cancelCampaign(req, res, app)
);


  // Flow routes
  app.post("/api/flow/start/:phoneNumber", (req, res) => startFlow(req, res, app));
  // Laravel commerce webhook → resume paused CommerceShop session.
  app.post("/api/flow/resume-port/:sessionKey", (req, res) => resumePort(req, res, app));
  // WABA inbound order webhook (no callback data) → phone-based lookup.
  app.post("/api/flow/resume-by-phone/:workspaceId/:customerPhone", (req, res) => resumeByPhone(req, res, app));
  // WhatsApp Form submission → resume the paused WaForm node, stamp
  // answers into session vars, advance through `out`.
  app.post("/api/flow/resume-form/:sessionKey", (req, res) => resumeForm(req, res, app));
  // Google Form submission (via Apps Script → Laravel → here). Body
  // carries session_id + answers; resumes the paused GoogleForm node.
  app.post("/api/flow-resume", (req, res) => resumeGoogleFormEndpoint(req, res, app));

  // WABA AI voice-call bridge — Laravel hands off the call when an
  // incoming WABA `connect` event lands AND an AI Voice Assistant
  // is configured for the workspace / conversation.
  app.post("/api/waba-call/answer",    (req, res) => wabaCallAnswer(req, res, app));
  app.post("/api/waba-call/terminate", (req, res) => wabaCallTerminate(req, res, app));
}
