
{ config, lib, pkgs, ... }:
let

  listNames = config.syscfg.server.db;
  containerNames = lib.concatMap (app: app.requires.databases) (builtins.attrValues config.syscfg.server.loadedContainers);
  allApps = lib.unique (listNames ++ containerNames);

in {
  config = lib.mkIf ( builtins.length allApps > 0) {
    services.postgresql = {
      enable = true;
      enableTCPIP = true;
      extensions = ps: with ps; [ vectorchord pgvector ];
      settings = {
        listen_addresses = lib.mkForce "*"; 
        shared_preload_libraries = "vchord";
      };
      authentication = pkgs.lib.mkOverride 10 ''
         # TYPE  DATABASE        USER            ADDRESS                 METHOD
         local   all             all                                     trust
         host    all             all             127.0.0.1/32            trust
         host    all             all             ::1/128                 trust
         host    all             all             10.0.0.0/8              scram-sha-256
         host    all             all             169.254.0.0/16          scram-sha-256
      '';
      ensureDatabases = map (name: "${name}_db") allApps;
      ensureUsers = map (name: { name = "${name}_user"; }) allApps;
    };
    services.postgresqlBackup = {
      enable = true;
      location = "/var/lib/postgresql/backups";
      startAt = "*-*-* 04:00:00"; # Runs every day at 4 AM
      backupAll = true; # Backs up all databases and roles
    };

    services.redis.servers."main" = {
      enable = true;
      port = 6379;
      bind = "*";
      settings.protected-mode = "no";
    };

    systemd.services.postgresql-init = {
      description = "Custom Postgres Setup (Ownership & Passwords)";
      after = [ "postgresql.service" ];
      wantedBy = [ "multi-user.target" ];
      
      serviceConfig = {
        Type = "oneshot";
        User = "postgres";
        RemainAfterExit = true;
      };

      script = ''
        ${pkgs.coreutils}/bin/sleep 20
        PSQL="${pkgs.postgresql}/bin/psql"
        ${lib.concatMapStringsSep "\n" (name: ''
          $PSQL -tAc "ALTER DATABASE ${name}_db OWNER TO ${name}_user;"
          $PSQL -d "${name}_db" -tAc "REINDEX DATABASE ${name}_db;"
          $PSQL -d "${name}_db" -tAc "ALTER DATABASE ${name}_db REFRESH COLLATION VERSION;"
          
          if [ -f "${config.sops.secrets."${lib.toUpper name}".path}" ]; then
            PASS=$(grep "^DB_PASSWORD=" "${config.sops.secrets."${lib.toUpper name}".path}" | cut -d'=' -f2-)
            if $PSQL -tAc "ALTER USER ${name}_user WITH PASSWORD '$PASS';" ; then
                echo "✅ Successfully set password for ${name}_user"
            else
                echo "❌ FAILED to set password for ${name}_user"
            fi
          fi
        '') allApps}
      '';
    };
  };
}
