module Webhooks
  class MediamtxController < ApplicationController
    skip_before_action :authenticate_request!

    before_action :verify_signature!

    def connect
      handle_event("connect")
    end

    def disconnect
      handle_event("disconnect")
    end

    def ready
      handle_event("ready")
    end

    def validate_publish
      session_id = params[:session_id] || extract_session_id(params[:path])
      token = params[:token]
      session = StreamSession.find_by(id: session_id)

      valid = session && session.publish_token == token && !session.ended?
      render json: { valid: valid }, status: valid ? :ok : :forbidden
    end

    private

    def handle_event(event)
      session_id = params[:session_id].presence || extract_session_id(params[:path])
      Webhooks::MediamtxHandler.new(
        event: event,
        session_id: session_id,
        metadata: params.permit!.to_h.except("controller", "action")
      ).call
      head :ok
    end

    def extract_session_id(path)
      path.to_s[%r{match_([0-9a-f-]+)}, 1]
    end

    def verify_signature!
      signature = request.headers["X-MediaMTX-Signature"]
      payload = request.raw_post.presence || request.query_string
      return if Webhooks::Signature.valid?(payload, signature)
      return if Rails.env.development? && signature.blank?

      head :unauthorized
    end
  end
end
