#!/usr/bin/perl
#
# Run it from the source's root directory (containing lib/ and t/) with
#    shellprompt$ prove -Ilib t/do-things.t

use English qw(-no_match_vars);
use common::sense;
use FindBin;
use lib "$FindBin::Bin/../lib";
# DBIx::Class is used implicitly via a 'Schema':
use Book::Schema;
use Test2::V0;
use Test2::Plugin::BailOnFail;

# Connect.
my $schema = Book::Schema->connect('dbi:Pg:dbname=pg_book_catalog', 'pgc_owner');
isa_ok($schema, ["Book::Schema"], "Acquired our Book::Schema object.");

# Acquire ResultSet for Author.
my $rset_author = $schema->resultset('Author');
isa_ok(
   $rset_author, ["DBIx::Class::ResultSet"],
   "Acquired DBIx::Class::ResultSet for Author."
);

# Create an author to do things with.
my $tolstoy0 = $rset_author->create({ name => "Tolstoy" });
isa_ok(
   $tolstoy0,
   ["Book::Schema::Result::Author"],
   "Created a Book::Schema::Result::Author object for Tolstoy."
);
is($tolstoy0->name, "Tolstoy", "And the author's name is Tolstoy.");
ok(defined $tolstoy0->id, "Author's id is defined.");
is($tolstoy0->when_created, undef, "Author's when_created remains undefined.");

my $tolstoy1 = $rset_author->find({ name => "Tolstoy" });
isa_ok(
   $tolstoy1, [ "Book::Schema::Result::Author" ],
   "Retrieved author object is a Book::Schema::Result::Author."
);
isa_ok(
   $tolstoy1->when_created, ["DateTime"],
   "The author object's when_created timestamp is inflated to a DateTime."
);
diag(sprintf("The when_created value is %s\n", $tolstoy1->when_created));

# Update the author object in memory.
is(
   $tolstoy1->name("Bacon"), "Bacon",
   "Locally updated the author's name to Bacon."
);

# Send the update to the database.
# Using ok() for confirming object identity because is() fails with
# "Deep recursion on subroutine..."
ok(
   $tolstoy1->update == $tolstoy1,
   "Sending the update returns the same object."
);

# A delete.
ok(
   $tolstoy1->delete == $tolstoy1,
   "Deleting the object returns the same object."
);

# Create a couple of authors for use in the Book tests.

my $austen = $rset_author->create({ name => "Jane Austen" });
isa_ok(
   $austen, ["Book::Schema::Result::Author"],
   "Created a Book::Schema::Result::Author object for Jane Austen."
);
is($austen->name, "Jane Austen", "The author's name is Jane Austen");

# For the second one, try new+insert instead of create.
my $dickens = $rset_author->new({ name => "Charles Dickens" });
isa_ok(
   $dickens, ["Book::Schema::Result::Author"],
   "Instantiated a Book::Schema::Result::Author object for Charles Dickens."
);
ok(! $dickens->in_storage, "Charles isn't in storage yet.");
$dickens->insert;
ok($dickens->in_storage, "Charles is in storage now.");
is($dickens->name, "Charles Dickens", "The author's name is Charles Dickens");

done_testing;
exit(0);
