//! Backblaze B2 file storage via S3-compatible API.
//!
//! Configuration (environment variables):
//!   B2_ACCESS_KEY_ID   — Application Key ID (preferred)
//!   B2_SECRET_ACCESS_KEY — Application Key secret (preferred)
//!   B2_KEY_ID          — Legacy alias for access key ID
//!   B2_APPLICATION_KEY — Legacy alias for secret key
//!   B2_BUCKET_NAME     — Bucket name (e.g. Nxtgauge-object)
//!   B2_ENDPOINT        — S3 endpoint (e.g. s3.eu-central-003.backblazeb2.com)
//!   B2_REGION          — Region (e.g. eu-central-003)
//!   B2_USE_PATH_STYLE  — true/false (default true)

use anyhow::{Context, Result};
use aws_config::{BehaviorVersion, Region};
use aws_credential_types::Credentials;
use aws_sdk_s3::Client;
use aws_sdk_s3::config::{Builder as S3ConfigBuilder, SharedCredentialsProvider};
use aws_sdk_s3::presigning::PresigningConfig;
use aws_sdk_s3::primitives::ByteStream;
use bytes::Bytes;
use std::time::Duration;
use uuid::Uuid;

#[derive(Clone)]
pub struct StorageClient {
    client: Option<Client>,
    bucket: String,
    public_base_url: String,
}

impl StorageClient {
    fn env_required(primary: &str, legacy: &str) -> String {
        std::env::var(primary)
            .or_else(|_| std::env::var(legacy))
            .unwrap_or_else(|_| panic!("{} (or {}) must be set", primary, legacy))
    }

    /// Build from environment variables. Panics if required vars are missing.
    /// Set MOCK_STORAGE=true to skip real B2 uploads and return dummy URLs.
    pub async fn from_env() -> Self {
        let mock = std::env::var("MOCK_STORAGE")
            .ok()
            .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
            .unwrap_or(false);

        let bucket = std::env::var("B2_BUCKET_NAME").unwrap_or_else(|_| "mock-bucket".to_string());
        let endpoint = std::env::var("B2_ENDPOINT")
            .unwrap_or_else(|_| "mock.storage.local".to_string())
            .trim_start_matches("https://")
            .trim_start_matches("http://")
            .to_string();
        let public_base_url = format!("https://{}/{}", endpoint, bucket);

        if mock {
            tracing::warn!("MOCK_STORAGE=true — file uploads will return dummy URLs");
            return Self { client: None, bucket, public_base_url };
        }

        let key_id = Self::env_required("B2_ACCESS_KEY_ID", "B2_KEY_ID");
        let app_key = Self::env_required("B2_SECRET_ACCESS_KEY", "B2_APPLICATION_KEY");
        let region = std::env::var("B2_REGION").expect("B2_REGION must be set");
        let use_path_style = std::env::var("B2_USE_PATH_STYLE")
            .ok()
            .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "y"))
            .unwrap_or(true);

        let creds = Credentials::new(key_id, app_key, None, None, "nxtgauge-storage");
        let endpoint_url = format!("https://{}", endpoint);

        let s3_config = S3ConfigBuilder::new()
            .behavior_version(BehaviorVersion::latest())
            .endpoint_url(endpoint_url)
            .region(Region::new(region))
            .credentials_provider(SharedCredentialsProvider::new(creds))
            .force_path_style(use_path_style)
            .build();

        let client = Client::from_conf(s3_config);
        Self { client: Some(client), bucket, public_base_url }
    }

    /// Upload bytes to B2. Returns the public URL.
    ///
    /// `prefix` — e.g. "portfolio", "resume", "profile"
    /// `ext`    — file extension without dot, e.g. "jpg", "pdf"
    pub async fn upload(&self, prefix: &str, ext: &str, data: Bytes, content_type: &str) -> Result<String> {
        let key = format!("{}/{}.{}", prefix, Uuid::new_v4(), ext);

        if let Some(client) = &self.client {
            client
                .put_object()
                .bucket(&self.bucket)
                .key(&key)
                .body(ByteStream::from(data))
                .content_type(content_type)
                .send()
                .await
                .context("B2 upload failed")?;
        }

        Ok(format!("{}/{}", self.public_base_url, key))
    }

    /// Derive the object key from a previously-stored full public URL, or pass a bare
    /// key straight through unchanged.
    fn key_from_url(&self, stored: &str) -> String {
        let prefix = format!("{}/", self.public_base_url);
        stored.strip_prefix(prefix.as_str()).unwrap_or(stored).to_string()
    }

    /// Mint a short-lived, signed URL for reading an object that was previously
    /// uploaded via `upload()`. `stored` is whatever `upload()` returned (a full
    /// public URL) or a bare object key.
    ///
    /// Callers must never persist or forward the plain stored URL/key directly to a
    /// browser as a working link — always mediate access through this method so the
    /// resulting URL expires and requires no reliance on the bucket being public.
    pub async fn presign(&self, stored: &str, ttl: Duration) -> Result<String> {
        let key = self.key_from_url(stored);

        let Some(client) = &self.client else {
            // MOCK_STORAGE=true / no client configured — nothing real to sign against.
            return Ok(stored.to_string());
        };

        let presigned = client
            .get_object()
            .bucket(&self.bucket)
            .key(&key)
            .presigned(PresigningConfig::expires_in(ttl).context("invalid presign expiry")?)
            .await
            .context("failed to presign B2 object")?;

        Ok(presigned.uri().to_string())
    }

    /// Delete a file by its full public URL (best-effort — logs on failure).
    pub async fn delete_by_url(&self, url: &str) {
        let Some(client) = &self.client else { return };
        let prefix = format!("{}/", self.public_base_url);
        if let Some(key) = url.strip_prefix(&prefix) {
            if let Err(e) = client
                .delete_object()
                .bucket(&self.bucket)
                .key(key)
                .send()
                .await
            {
                tracing::warn!("B2 delete failed for key={}: {}", key, e);
            }
        }
    }
}
