# Copyright (c) 2025 Yuki Kimoto
# MIT License

class Mojolicious::Command::Cgi extends Mojolicious::Command {
  version_from Mojolicious;
  
  use Mojo::Server::CGI;
  use Mojo::Util;
  use Fn;
  
  has description : rw string
    get {
      unless (exists $self->{description}) {
        $self->{description} = "Start application with CGI";
      }
      return $self->{description};
    }
  ;
  
  has usage : rw string
    get {
      unless (exists $self->{usage}) {
        $self->{usage} = <<'EOS';
Usage: APPLICATION cgi [OPTIONS]

  ./myapp.spvm cgi

Options:
  -h, --help          Show this summary of available options
      --home <path>   Path to home directory of your application, defaults to
                      the value of MOJO_HOME or auto-detection
  -m, --mode <name>   Operating mode for your application, defaults to the
                      value of MOJO_MODE/PLACK_ENV or "development"
      --nph           Enable non-parsed-header mode

EOS
      }
      
      return $self->{usage};
    }
  ;
  
  method run : void ($args : string[]) {
    
    my $values_h = Hash->new({
      nph => 0,
    });
    
    my $specs = [
      "nph",
    ];
    
    eval { Mojo::Util->getopt(my $_ = [$args], $values_h, $specs); }
    
    if ($@) {
      die $self->usage;
    }
    
    my $nph = $values_h->{"nph"}->(int);
    
    my $server = Mojo::Server::CGI->new;
    
    $server->set_app($self->app);
    
    $server->set_nph($nph);
    
    $server->run;
  }

}