//! atproto-static-web   A simple web viewer for AT Proto.
//! Copyright (C) 2025  AverageHelper
//!
//! This program is free software: you can redistribute it and/or modify
//! it under the terms of the GNU General Public License as published by
//! the Free Software Foundation, either version 3 of the License, or
//! (at your option) any later version.
//!
//! This program is distributed in the hope that it will be useful,
//! but WITHOUT ANY WARRANTY; without even the implied warranty of
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//! GNU General Public License for more details.
//!
//! You should have received a copy of the GNU General Public License
//! along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::{
	constants::USER_AGENT,
	env::Env,
	server::{cors::cors, lang::content_language, routes, shield},
};
use reqwest::Client;
use rocket::{Build, Rocket, catchers, routes};

pub fn http_service(env: Env) -> Rocket<Build> {
	simple_logger::init_with_level(env.log_level()).unwrap();

	#[cfg(debug_assertions)]
	let default_config = rocket::Config::debug_default();
	#[cfg(not(debug_assertions))]
	let default_config = rocket::Config::release_default();

	let config = rocket::Config {
		ident: rocket::config::Ident::try_new(USER_AGENT).expect("ascii"),
		address: env.address(),
		port: env.http_port(),
		log_level: match env.log_level() {
			log::Level::Trace | log::Level::Debug => rocket::config::LogLevel::Debug,
			log::Level::Info => rocket::config::LogLevel::Normal,
			log::Level::Warn | log::Level::Error => rocket::config::LogLevel::Critical,
		},
		..default_config
	};

	let client = Client::builder().user_agent(USER_AGENT).build().unwrap();

	rocket::build()
		.configure(config)
		.attach(shield::shield())
		.attach(shield::more_shield())
		.attach(cors())
		.attach(content_language())
		.manage(client)
		.manage(env)
		.mount(
			"/",
			routes![
				routes::index,
				routes::favicon,
				routes::robots,
				routes::fonts,
				routes::profile,
				routes::post
			],
		)
		.register("/", catchers![routes::catchers::error])
}
