{ pkgs ? import <nixpkgs> {} }:

let
  lookbook = pkgs.buildGoModule {
    pname = "lookbook";
    version = "0.1.0";
    src = ./.;
    
    vendorHash = null;
    
    env.GOPRIVATE = "git.soup.land";
    
    # Build the server binary
    subPackages = [ "cmd/server" ];
    
    postInstall = ''
      mv $out/bin/server $out/bin/lookbook
    '';
    
    meta = with pkgs.lib; {
      description = "Lookbook";
      homepage = "https://git.soup.land/soup/lookbook";
    };
  };
in
{
  package = lookbook;
  
  nixosModule = { config, lib, pkgs, ... }:
    let 
      cfg = config.services.lookbook;
    in {
      options.services.lookbook = {
        enable = lib.mkEnableOption "lookbook service";
        
        address = lib.mkOption {
          type = lib.types.str;
          default = "127.0.0.1:8080";
          description = "Address to listen on";
        };
        
        databaseUrl = lib.mkOption {
          type = lib.types.str;
          description = "PostgreSQL connection URL";
        };
        
        user = lib.mkOption {
          type = lib.types.str;
          default = "lookbook";
          description = "User to run the service as";
        };
        
        group = lib.mkOption {
          type = lib.types.str;
          default = "lookbook";
          description = "Group to run the service as";
        };
      };
      
      config = lib.mkIf cfg.enable {
        users.users.${cfg.user} = {
          isSystemUser = true;
          group = cfg.group;
        };
        users.groups.${cfg.group} = {};
        
        # Add lookbook binary to system PATH
        environment.systemPackages = [ lookbook ];
        
        systemd.services.lookbook = {
          description = "Lookbook";
          wantedBy = [ "multi-user.target" ];
          after = [ "network.target" "postgresql.service" ];
          requires = [ "postgresql.service" ];
          
          environment = {
            DATABASE_URL = cfg.databaseUrl;
            ADDR = cfg.address;
          };
          
          serviceConfig = {
            Type = "simple";
            User = cfg.user;
            Group = cfg.group;
            ExecStartPre = "${lookbook}/bin/lookbook -migrate";
            ExecStart = "${lookbook}/bin/lookbook web";
            Restart = "always";
            RestartSec = 5;
          };
        };
      };
    };
}
