use strict;
use warnings;
use Test::More;
use Test::Exception;

use SQL::Abstract::More;
use SQL::Abstract::Test import => ['eq_sql'];
use List::MoreUtils qw/any/;

plan tests => 2;


my $sqla  = SQL::Abstract::More->new;

my $result = $sqla->join(
  'table',
  { operator => '=>',
    condition => { '%1$s.table_id' => {-ident => '%2$s.table_id'},
                   '%2$s.date'     => {'>' => {-ident => '%1$s.date'}},
                   '%2$s.event_id' => 1}},
  'table_log'
);

# we don't know the order of conditions generated by SQL::Abstract;
# but unfortunately, SQL::Abstract::Test is not clever enough to apply
# commutativity on AND, so we have to do it by hand

my @conditions = (
  'table_log.date     > table.date',
  'table.table_id     = table_log.table_id',
  'table_log.event_id = ?',
);

my @possible_SQL = map {"table LEFT OUTER JOIN table_log ON "
                        . join(' AND ', @$_) } permutations(@conditions);

ok (any { eq_sql($result->{sql}, $_) } @possible_SQL);
is_deeply ($result->{bind}, [1]);



sub permutations {
  return \@_ if @_ < 2;

  my @result;
  for my $i (0 .. $#_) {
    my @tail = @_;
    my $head = splice(@tail, $i, 1);
    push @result, map {[$head, @$_ ]} permutations(@tail);
  }
  return @result;
}
