{ config, lib, ... }:

with lib;

let
  cfg = config.settings.containers.immich;
in {
  options = {
    settings.containers.immich.enable = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = ''
        Enable immich container
      '';
    };
  };

  config = mkIf cfg.enable {
    services.podman.containers.immich-server = {
      image = "ghcr.io/immich-app/immich-server:release";
      network = "proxy";
      volumes = [
        "%h/containers/immich/upload:/usr/src/app/upload"
        "/etc/localtime:/etc/localtime:ro" 
      ];
      extraConfig = {
        Unit = {
          After = [
            "podman-immich-redis.service"
            "podman-immich-database.service"
          ];
          Requires = [
            "podman-immich-redis.service"
            "podman-immich-database.service"
          ];
        };
      };
      environment = {
        DB_PASSWORD = "changeme";
        DB_USERNAME = "postgres";
        DB_DATABASE_NAME = "immich";
        DB_HOSTNAME = "immich-database";
        REDIS_HOSTNAME = "immich-redis";
      };
    };

    services.podman.containers.immich-machine-learning = {
      image = "ghcr.io/immich-app/immich-machine-learning:release";
      network = "proxy";
      volumes = [
        "%h/containers/immich/model-cache:/cache"
      ];
    };

    services.podman.containers.immich-redis = {
      image = "docker.io/valkey/valkey:8-bookworm@sha256:42cba146593a5ea9a622002c1b7cba5da7be248650cbb64ecb9c6c33d29794b1";
      network = "proxy";
    };

    services.podman.containers.immich-database = {
      image = "docker.io/tensorchord/pgvecto-rs:pg14-v0.2.0@sha256:739cdd626151ff1f796dc95a6591b55a714f341c737e27f045019ceabf8e8c52";
      network = "proxy";
      volumes = [
        "%h/containers/immich/database-data:/var/lib/postgresql/data"
      ];
      environment = {
        POSTGRES_PASSWORD = "changeme";
        POSTGRES_USER = "postgres";
        POSTGRES_DB = "immich";
        POSTGRES_INITDB_ARGS = "--data-checksums";
      };
      exec = ''postgres -c shared_preload_libraries=vectors.so -c 'search_path="$$user", public, vectors' -c logging_collector=on -c max_wal_size=2GB -c shared_buffers=512MB -c wal_compression=on'';
    };

    settings.containers.caddy.routes.tbmrs.routes.immich = {
      host = "photos";
      url = "immich-server:2283"; 
    };
  };
}
