{ config, lib, ... }:

with lib;

let
  cfg = config.settings.containers.caddy;

  toInternal = name: routesDef: {
    name = name;
    host = routesDef.host;
    url = routesDef.url;
  };

  generateRoutes = domain: entries: lib.concatMapStrings (route: ''
    @${route.name} host ${route.host}.${domain}
    handle @${route.name} {
      reverse_proxy ${route.url}
    }
  '') entries;

  routesOption = lib.mkOption {
    type = types.attrsOf (types.submodule {
      options = {
        url = mkOption {
          type = types.str;
        };
        host = mkOption {
          type = types.str;
        };
      };
    });
  };
in {
  options = {
    settings.containers.caddy.enable = mkOption {
      type = lib.types.bool;
      default = false;
      description = ''
        Enable caddy container
      '';
    };

    settings.containers.caddy.routes = mkOption {
      type = lib.types.attrsOf (types.submodule {
        options = {
          routes = routesOption;
          domain = mkOption {
            type = types.str;
          };
        };       
      });
    };
  };

  config = mkIf cfg.enable {
    services.podman.containers.caddy = {
      image = "localhost/tboomers/caddy-custom:latest";
      network = "proxy";
      networkAlias = [
        "mail.tbmrs.nl"
      ];
      ports = [
        "1080:80"
        "1443:443"
      ];
      volumes = [
        "%h/containers/caddy/Caddyfile:/etc/caddy/Caddyfile"
        "%h/containers/caddy/acme_key:/etc/caddy/acme_key"
        "%h/containers/caddy/data:/data"
      ];
    };

    settings.containers.caddy.routes = {
      tbmrs.domain = "tbmrs.nl"; 
      tbmrs-local.domain = "local.tbmrs.nl"; 
    };

    home.file."containers/caddy/Caddyfile".text = ''
      *.tbmrs.nl, tbmrs.nl {
        tls {
          dns transip xeovalyte /etc/caddy/acme_key
          resolvers 1.1.1.1
        }

        ${generateRoutes cfg.routes.tbmrs.domain (mapAttrsToList toInternal cfg.routes.tbmrs.routes)}
      }

      *.local.tbmrs.nl {
        tls {
          dns transip xeovalyte /etc/caddy/acme_key
          resolvers 1.1.1.1
        }

        ${generateRoutes cfg.routes.tbmrs-local.domain (mapAttrsToList toInternal cfg.routes.tbmrs-local.routes)}
      }
    '';
  };
}
