### ----------------------------------------------------
### -- RedFactory
### -- Licenses: Artistic-2.0
### -- Authors: 
### -- File: t/02-example.rakutest
### ----------------------------------------------------
use Test;
use Red;
use RedFactory;

model Post {...}

model Person {
   has UInt    $.id          is serial;
   has Str     $.first-name  is column;
   has Str     $.last-name   is column;
   has Str     $.email       is column;
   has Instant $.disabled-at is column{ :nullable };
   has Post    @.posts       is relationship(*.author-id, :model(Post));
}

model Post {
    has UInt   $.id        is serial;
    has Str    $.title     is column;
    has Str    $.body      is column;
    has UInt   $!author-id is referencing(*.id, :model(Person));
    has Person $.author    is relationship(*.author-id, :model(Person));
}

factory "person", :model(Person), {

   .first-name = "john";
   .last-name  = "doe";
   .email      = -> $_, :$number = .counter-by-model { "{ .first-name }{ $number }@domain.com" }

   .posts      = -> :$num-of-posts = 0 { factory-args $num-of-posts, "post" }

   trait "disabled", {
      .disabled-at = now
   }
}

factory "post", :model(Post), {

    .title = { "Post title { .counter-by-model }" };
    .body  = -> $_, :$title-repetition = 3 { (.title ~ "\n") x $title-repetition }

}

RedFactory.run: {
   given .create: "person" {
    is .first-name, "john";
    is .last-name,  "doe";
    is .email,      "john1@domain.com";
   }

   given .create: "person", :first-name<peter>, :last-name<parker> {
    is .first-name, "peter";
    is .last-name,  "parker";
    is .email,      "peter2@domain.com";
   }

   given .create: "person", :email<bla@ble.com> {
    is .first-name, "john";
    is .last-name,  "doe";
    is .email,      "bla@ble.com";
   }

   given .create: "person", "disabled" {
    is .first-name, "john";
    is .last-name,  "doe";
    is .email,      "john4@domain.com";
    ok .disabled-at;
   }

   given .create: "person", :PARS{ :42number } {
    is .first-name, "john";
    is .last-name,  "doe";
    is .email,      "john42@domain.com";
   }

   is-deeply
    factory-args("person", :PARS{ :2num-of-posts }),
    %(
        :first-name<john>,
        :last-name<doe>,
        :email<john6@domain.com>,
        :posts(
            %(
                :title("Post title 1"),
                :body("Post title 1\n" x 3),
            ).Map,
            %(
                :title("Post title 2"),
                :body("Post title 2\n" x 3),
            ).Map,
        )
    ).Map;

    given factory-create("person", :PARS{ :2num-of-posts }) {
        is .first-name, "john";
        is .last-name, "doe";
        is .email, "john7@domain.com";
        is .posts[0].title, "Post title 3";
        is .posts[0].body, "Post title 3\n" x 3;
        is .posts[1].title, "Post title 4";
        is .posts[1].body, "Post title 4\n" x 3;
    }
}

done-testing


