use fastly::http::{Method, StatusCode};
use fastly::{mime, panic_with_status, Request, Response};
use serde::Deserialize;

use qrcode_generator::QrCodeEcc;

#[derive(Deserialize)]
struct CodeParams {
    url: Option<String>,
}

fn generate_code(content: &str) {
    // Send the response headers to the client and get a writable stream
    let resp = Response::from_status(StatusCode::OK).with_content_type(mime::IMAGE_PNG);
    let mut body = resp.stream_to_client();

    // Encode the QR code image as a PNG and stream it to the client
    qrcode_generator::to_png_to_writer_from_str(content, QrCodeEcc::Low, 512, &mut body).unwrap();
}

// Cannot use #[fastly::main] here because we need to send a streaming body
fn main() {
    let req = Request::from_client();

    match (req.get_method(), req.get_path()) {
        (&Method::GET, "/qr.png") => {
            // Fetch target URL from query string
            let params: CodeParams = req.get_query().unwrap();

            if let Some(url) = params.url {
                // Limit the content length
                if url.len() > 128 {
                    panic_with_status!(StatusCode::BAD_REQUEST, "URL too long");
                }

                // Generate the image and send it to the client
                generate_code(&url);
            } else {
                panic_with_status!(StatusCode::BAD_REQUEST, "No URL provided");
            }
        }
        _ => {
            panic_with_status!(StatusCode::NOT_FOUND);
        }
    }
}