import { Controller, Headers, Post, Req, UnauthorizedException } from "@nestjs/common";
import { LiveKitService } from "./livekit.service";
import * as messaging from "@slackwsh/messaging";

/**
 * LiveKit and Twilio ingress — no user JWT. LiveKit is HMAC/JWT-verified
 * inside LiveKitService; Twilio inbound is a TwiML responder gated on the
 * configured PSTN number mapping to a workspace.
 */
@Controller("webhooks")
export class CallsWebhooksController {
  constructor(private readonly livekit: LiveKitService) {}

  @Post("livekit")
  async ingestLivekit(@Req() req: { body?: unknown }, @Headers("authorization") authorization?: string) {
    const raw = typeof req.body === "string" ? req.body : JSON.stringify(req.body ?? {});
    await this.livekit.handleWebhook(raw, authorization);
    return { ok: true };
  }

  @Post("twilio/voice")
  async twilioVoice(@Req() req: { body?: unknown }) {
    const body = (req.body ?? {}) as Record<string, string>;
    const to = String(body.To ?? body.to ?? "");
    const from = String(body.From ?? body.from ?? "");
    const workspaceId = messaging.workspaceIdForInboundPstn(to);
    if (!workspaceId) throw new UnauthorizedException("unknown PSTN number");
    const cfg = this.livekit.config();
    if (!cfg) {
      return `<Response><Say>Connect is not available right now.</Say></Response>`;
    }
    return `<Response><Say>Connecting you now.</Say><Dial>${escapeXml(from)}</Dial></Response>`;
  }
}

function escapeXml(value: string) {
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
