// Simple mock upstream HTTP server for testing
// Responds to basic requests with test data

use std::env;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::process;
use std::thread;

fn handle_client(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    let _bytes_read = stream.read(&mut buffer).unwrap();

    let request = String::from_utf8_lossy(&buffer);
    let response = if request.starts_with("GET /health") {
        "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 2\r\n\r\nOK"
    } else if request.starts_with("GET /slow") {
        thread::sleep(std::time::Duration::from_secs(5));
        "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 4\r\n\r\nSlow"
    } else if request.starts_with("GET /error") {
        "HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nError"
    } else if request.starts_with("GET /cache") {
        "HTTP/1.1 200 OK\r\nCache-Control: public, max-age=3600\r\nContent-Type: text/plain\r\nContent-Length: 6\r\n\r\nCached"
    } else {
        "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 11\r\n\r\nMock Server"
    };

    stream.write_all(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

fn main() {
    let port = env::args()
        .nth(1)
        .or_else(|| env::var("PORT").ok())
        .unwrap_or_else(|| "3001".to_string());

    let addr = format!("0.0.0.0:{}", port);
    let listener = match TcpListener::bind(&addr) {
        Ok(listener) => listener,
        Err(err) => {
            eprintln!("Mock upstream failed to bind on {}: {}", addr, err);
            process::exit(1);
        }
    };

    println!("Mock upstream server listening on {}", addr);

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                thread::spawn(|| handle_client(stream));
            }
            Err(e) => {
                eprintln!("Connection failed: {}", e);
            }
        }
    }
}
