#!/usr/bin/perl

use English qw(-no_match_vars);
use common::sense;
use FindBin;
use lib "$FindBin::Bin/../lib";
use Book::Schema;
use Test2::V0;
use Test2::Plugin::BailOnFail;

# Connect and acquire an author.
my $schema = Book::Schema->connect('dbi:Pg:dbname=pg_book_catalog', 'pgc_owner');
my $rset_author = $schema->resultset('Author');
my $charles = $rset_author->find({ name => "Charles Dickens" });

# Attempt to delete an author who has books.
my $exception = dies { $charles->delete; };
isa_ok(
   $exception, ["DBIx::Class::Exception"],
   "DBIx::Class::Exception raised by attempt to delete."
);
like(
   $exception, qr/violates foreign key constraint/,
   "Error on delete 'violates foreign key constraint'."
);

# Attempt to null a not-null column.
$exception = dies { $charles->update({ name => undef }); };
like(
   $exception, qr/violates not-null constraint/,
   "Error on update 'violates not-null constraint'."
);

# Attempt to insert a duplicate author.
$exception = dies {
   $rset_author->create({ name => "Charles Dickens" });
};
like(
   $exception, qr/violates unique constraint/,
   "Error on insert 'violates unique constraint'."
);

# Delete the test books.
my $rset_book = $schema->resultset('Book');
my $rset_tbooks = $rset_book->search_rs({ gutenberg_id => { '<' => 0 } });
$rset_tbooks->delete;

# Delete the test authors.
my $rset_tauthors = $schema->resultset('Author')->search_rs(
   { name => { 'in' => [ "Charles Dickens", "Jane Austen" ] } },
);
$rset_tauthors->delete;

done_testing;
