#!perl
use strict;
use warnings;

use Test::More;
use Test::Exception;
use DBIx::Fast;

eval "use DBD::SQLite 1.74";
plan skip_all => "DBD::SQLite 1.74" if $@;

my $db = DBIx::Fast->new( SQLite => 't/db/test.db' , PrintError => 1 , RaiseError => 0);

my $test = {
    user => 'tester',
    password => 'mypass'
};

$db->_dsn_to_dbi('mariadb://'.$test->{user}.':'.$test->{password}.'@server:3306/db');

is $db->args->{Auth}->{user},$test->{user},'Args Auth : user';
is $db->args->{Auth}->{password},$test->{password},'Args Auth : password';

my $DSN = {
    'postgresql://user@127.0.0.1:5432/dbname?reconnect=60' => "dbi:Pg:dbname=dbname;host=127.0.0.1;port=5432",
    'postgresql://user:123456@127.0.0.1:5432/dbname' => "dbi:Pg:dbname=dbname;host=127.0.0.1;port=5432",
    'postgres://user:123456@db:5432/dbname' => "dbi:Pg:dbname=dbname;host=db;port=5432",
    'mysql://user:pass@localhost:3306/dbname?get-server-public-key=true' => "dbi:mysql:dbname=dbname;host=localhost;port=3306",
    'mysql://user:pass@localhost:3306/dbname?get-server-public-key=true&k=v&k=v&k=v' => "dbi:mysql:dbname=dbname;host=localhost;port=3306",
    'mariadb://user:pass@server:3306/db' => "dbi:MariaDB:dbname=db;host=server;port=3306",
};

for my $Key (keys %{$DSN}) {
    is $db->_dsn_to_dbi($Key),$DSN->{$Key},'_dsn_to_dbi : '.$Key;
}

throws_ok { $db->_dsn_to_dbi('SSS://sql:pass@host:/dbname') }
    qr/Exception: _dsn_to_dbi/, '_dsn_to_dbi : Bad string';
throws_ok { $db->_dsn_to_dbi('sql://user@host/dbname') }
    qr/Exception: _dsn_to_dbi/, '_dsn_to_dbi : Bad DSN';

# --- 0.17: additive DSN acceptance (must not reject valid forms) -----------

# SQLite in-memory in the native DBI form (database part contains colons).
is $db->_check_dsn('dbi:SQLite::memory:'), 'dbi:SQLite::memory:',
    'dbi:SQLite::memory: is accepted unchanged';

# Case-insensitive dbi: prefix.
is $db->_check_dsn('DBI:SQLite:dbname=x'), 'DBI:SQLite:dbname=x',
    'uppercase DBI: prefix is accepted';

# Credential-less URI (socket / peer auth): userinfo is optional.
is $db->_dsn_to_dbi('mariadb://localhost/appdb'),
    'dbi:MariaDB:dbname=appdb;host=localhost',
    'credential-less mariadb:// URI (socket auth) builds a DSN';
is $db->_dsn_to_dbi('postgres://pghost:5432/appdb'),
    'dbi:Pg:dbname=appdb;host=pghost;port=5432',
    'credential-less postgres:// URI with port';

# A dbi: DSN with no driver is still rejected.
throws_ok { $db->_check_dsn('dbi::nodriver') } qr/Exception/,
    'a dbi: DSN with no driver is rejected';

done_testing();
