//! Controller for the `GitServer` CRD — Deployment + HTTP Svc + SSH Svc + PVC.

use crate::context::ReconcileState;
use crate::controller::app::{apply_deployment, apply_service, patch_status};
use crate::controller::helpers::{child_meta, env_var_to_json, merge_env, owner_ref, query_deployment_status, std_labels};
use crate::crd::{GitServer, GitServerSpec};
use serde_json::{Value, json};
use std::sync::Arc;
use tracing::info;

pub async fn reconcile(gs: Arc<GitServer>, ctx: Arc<ReconcileState>) -> Result<(), kube::Error> {
    let ns = gs.metadata.namespace.as_deref().unwrap_or("default");
    let name = gs.metadata.name.as_deref().unwrap_or("");
    let spec = &gs.spec;
    let client = &ctx.client;

    let or = owner_ref(&gs.metadata, &gs.api_version, &gs.kind);
    let labels = std_labels();

    // ---- PVC ----
    let pvc = build_pvc(ns, name, spec, &or, &labels);
    apply_pvc(client, ns, &format!("{}-repos", name), &pvc).await?;

    // ---- Deployment ----
    let deployment = build_deployment(ns, name, spec, &or, &labels);
    apply_deployment(client, ns, name, &deployment).await?;

    // ---- HTTP Service ----
    let http_svc = build_http_service(ns, name, spec, &or, &labels);
    apply_service(client, ns, &format!("{}-http", name), &http_svc).await?;

    // ---- SSH Service ----
    let ssh_svc = build_ssh_service(ns, name, spec, &or, &labels);
    apply_service(client, ns, &format!("{}-ssh", name), &ssh_svc).await?;

    // ---- Status ----
    let (ready_replicas, phase) = query_deployment_status(client, ns, name).await?;
    let status = json!({ "status": { "readyReplicas": ready_replicas, "phase": phase } });
    patch_status::<GitServer>(client, ns, name, &status).await?;

    Ok(())
}

fn build_deployment(
    ns: &str,
    name: &str,
    spec: &GitServerSpec,
    or: &crate::crd::OwnerReference,
    labels: &std::collections::BTreeMap<String, String>,
) -> Value {
    let env = merge_env(&[], &spec.env);
    let image = if spec.image.is_empty() {
        "myapp/gitserver:latest".to_string()
    } else {
        spec.image.clone()
    };
    let pull = if spec.image_pull_policy.is_empty() {
        "IfNotPresent".to_string()
    } else {
        spec.image_pull_policy.clone()
    };
    let resources = super::app::build_resources(&spec.resources);

    json!({
        "metadata": child_meta(name, ns, or, labels.clone()),
        "spec": {
            "replicas": 1,
            "selector": { "matchLabels": labels },
            "template": {
                "metadata": { "labels": labels.clone() },
                "spec": {
                    "containers": [{
                        "name": "gitserver",
                        "image": image,
                        "ports": [
                            { "name": "http", "containerPort": spec.http_port },
                            { "name": "ssh",  "containerPort": spec.ssh_port }
                        ],
                        "env": env.iter().map(env_var_to_json).collect::<Vec<_>>(),
                        "imagePullPolicy": pull,
                        "resources": resources,
                        "volumeMounts": [{ "name": "git-repos", "mountPath": "/data/repos" }]
                    }],
                    "volumes": [{
                        "name": "git-repos",
                        "persistentVolumeClaim": { "claimName": format!("{}-repos", name) }
                    }]
                }
            }
        }
    })
}

fn build_http_service(
    ns: &str,
    name: &str,
    spec: &GitServerSpec,
    or: &crate::crd::OwnerReference,
    labels: &std::collections::BTreeMap<String, String>,
) -> Value {
    json!({
        "metadata": child_meta(&format!("{}-http", name), ns, or, labels.clone()),
        "spec": {
            "ports": [{ "port": spec.http_port, "targetPort": spec.http_port, "name": "http" }],
            "selector": labels.clone(),
            "type": "ClusterIP"
        }
    })
}

fn build_ssh_service(
    ns: &str,
    name: &str,
    spec: &GitServerSpec,
    or: &crate::crd::OwnerReference,
    labels: &std::collections::BTreeMap<String, String>,
) -> Value {
    json!({
        "metadata": child_meta(&format!("{}-ssh", name), ns, or, labels.clone()),
        "spec": {
            "ports": [{ "port": spec.ssh_port, "targetPort": spec.ssh_port, "name": "ssh" }],
            "selector": labels.clone(),
            "type": spec.ssh_service_type
        }
    })
}

fn build_pvc(
    ns: &str,
    name: &str,
    spec: &GitServerSpec,
    or: &crate::crd::OwnerReference,
    labels: &std::collections::BTreeMap<String, String>,
) -> Value {
    json!({
        "metadata": child_meta(&format!("{}-repos", name), ns, or, labels.clone()),
        "spec": {
            "accessModes": ["ReadWriteOnce"],
            "resources": { "requests": { "storage": spec.storage_size } }
        }
    })
}

async fn apply_pvc(
    client: &kube::Client,
    ns: &str,
    name: &str,
    body: &Value,
) -> Result<(), kube::Error> {
    let api: kube::Api<crate::crd::JsonResource> = kube::Api::namespaced(client.clone(), ns);
    let jr = crate::crd::JsonResource::new(Default::default(), body.clone());
    match api.get(name).await {
        Ok(_) => {
            /* already exists, don't replace PVC */
            Ok(())
        }
        Err(kube::Error::Api(e)) if e.code == 404 => {
            info!(name, ns, "creating gitserver pvc");
            let _ = api.create(&kube::api::PostParams::default(), &jr).await?;
            Ok(())
        }
        Err(e) => Err(e),
    }
}
