//! 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 rocket::{
	Request, Response, State,
	fairing::{Fairing, Info, Kind},
	http::{Header, hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN},
};

use crate::env::Env;

/// A Rocket [Fairing] that sets appropriate [CORS] headers.
///
/// [Fairing]: https://rocket.rs/guide/v0.5/fairings/#fairings
/// [CORS]: https://developer.mozilla.org/en-US/docs/Glossary/CORS
pub fn cors() -> Cors {
	Cors
}

pub struct Cors;

#[rocket::async_trait]
impl Fairing for Cors {
	fn info(&self) -> Info {
		Info {
			name: "CORS Headers",
			kind: Kind::Response,
		}
	}

	async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
		let env = req.guard::<&State<Env>>().await.expect("env");
		let host = env.base_url().host_str().expect("host");

		res.set_header(Header::new(ACCESS_CONTROL_ALLOW_ORIGIN.as_str(), host));
	}
}
