#!env perl6
use Red::Cli;
use Red::Do;
use Red::Database;

my %*SUB-MAIN-OPTS =
  :named-anywhere,
;

my $*RED-DEBUG = False;

proto MAIN(Str :$I, Bool :$debug, |) {
    dyn-lib .split: "," with $I;
    $*RED-DEBUG = $debug;
    {*}
}

#| List tables in database
multi MAIN(
    "list-tables",
    Str  :$driver!,
    *%pars
) {
    my $*RED-DB = database($driver, |%pars);
    .say for list-tables :$driver, |%pars
}

#| Generate stub code to access models from database schema
multi MAIN(
    "print-stub",
    Str  :$schema-class,
    Str  :$driver!,
    *%pars
) {
    my $*RED-DB = database($driver, |%pars);
    say gen-stub-code :$schema-class, :$driver, |%pars
}


#| Generates migration plan to upgrade database schema
multi MAIN(
    "migration-plan",
    Str :$model!,
    Str :$require = $model,
    Str :$driver!,
    *%pars
) {
    my $*RED-DB = database($driver, |%pars);
    migration-plan :$model, :$require, :$driver, |%pars
}

#| Generates models' code from database schema
multi MAIN(
    "generate-code",
    Str  :$path!    where { not .defined or .IO.d or $_ eq "-" or fail "Path $_ does not exist." },
    Str  :$from-sql where { not .defined or .IO.f or $_ eq "-" or fail "SQL $_ do not exist." },
    Str  :$schema-class,
    Bool :$print-stub       = False,
    Bool :$no-relationships = False,
    #Bool :$stub-only,
    Str  :$driver!,
    *%pars
) {
    my $*RED-DB = database($driver, |%pars);
    generate-code
            :$path,
            :$from-sql,
            :$schema-class,
            :$print-stub,
            :$no-relationships,
            :$driver,
            |%pars
}

#| Prepare database
multi MAIN(
        "prepare-database",
        Bool :$populate,
        Str  :$models!,
        Str  :$driver!,
        *%pars
) {
    $GLOBAL::RED-DB = database $driver, |%pars;
    prepare-database :$populate, :$models, :$driver, |%pars
}

sub dyn-lib(@libs) {
	qq[use lib "{ $_ }"].EVAL for @libs
}
